C language -- string and string function

Posted by JesuZ on Tue, 04 Jan 2022 08:52:05 +0100

String function

The C library provides many functions for processing strings. These function prototypes are in string H header file.

strlen() function

The strlen() function counts the length of a string.
Example:

#include<stdio.h>
#include<string.h>
int main(void)
{
	char str[] = "This is a string.";

	printf("str has %d characters.\n", strlen(str));

	return 0;
}

Operation results:

It can be seen that the length calculated by this function does not take '\ 0'.

You can write a function to modify the length of a string.

void fit(char* str, int size)
{
	if (strlen(str) > size)
		str[size] = '\0';
}

strcat() function

Used to splice strings. The function takes two strings as parameters, appends the backup of the second string to the end of the first string, and takes the new string formed after splicing as the first string, and the second string remains unchanged.

Usage:

#include<stdio.h>
#include<string.h>
#include<assert.h>
#define SIZE 128
char* s_gets(char* st, int n);

int main(void)
{
	char str1[SIZE] = "Hello, my name is Tarzan.";
	char str2[SIZE];
	puts("What's your job?");
	if (s_gets(str2, SIZE))
	{
		strcat_s(str1, str2);
		puts("After strcat:");
		puts(str1);
	}
	else
	{
		puts("End of file encountered.");
	}

	return 0;
}

char* s_gets(char* st, int n)
{
	assert(st != nullptr);
	char* ret_val = fgets(st, n, stdin);
	int i = 0;

	if (ret_val)
	{
		while (st[i] != '\n' && st[i] != '\0')
			++i;
		if (st[i] == '\n')
			st[i] = '\0';
		else
			while (getchar() != '\n')
				continue;
	}
	return ret_val;
}

Operation results:

strncat() function

The strcat() function cannot check whether the first array can hold the second string. The third parameter of the strncat() function specifies the maximum number of characters to be added.
For example:

strnact(str1, str2, 10);

strcmp() function

This function compares the size of the string content, not the string address.
Program example:

#include<stdio.h>
#include<string.h>

int main(void)
{
	 char str[4][10] = {
		"China",
		"Russia",
		"America",
		"Japan"
	};
	 int i, j;
	 for (i = 1, j = 0; i < 4; ++i)
	 {
		 if (strcmp(str[i], str[j]) > 0)
			 j = i;
	 }
	 printf("%s\n", str[j]);
	 return 0;
}

This program prints the largest string after several string comparisons
Operation results:

Return value of strcmp()

Take the program directly:

#include<stdio.h>
#include<string.h>

int main(void)
{
	printf("strcmp(\"A\", \"A\") is ");
	printf("%d\n", strcmp("A", "A"));

	printf("strcmp(\"A\", \"B\") is ");
	printf("%d\n", strcmp("A", "B"));

	printf("strcmp(\"B\", \"A\") is ");
	printf("%d\n", strcmp("B", "A"));
	return 0;
}

Operation results:

This means that if the first string in the alphabet precedes the second string, the strcmp() function returns a negative number, and vice versa.

What if the first few characters of two strings are the same?
In general, strcmp() compares each character at a time until it finds the first different pair of characters.

strncmp() function

When comparing two strings, this function can compare different characters, or only the number of characters specified by the third parameter.
Example:

#include<stdio.h>
#include<string.h>
#define SIZE 6
int main(void)
{
	const char* str[SIZE] =
	{
		"astronomy", "astounding",
		"astrophysics", "ostracize",
		"asterism", "astrophobia"
	};
	int i = 0;
	for (i = 0; i < SIZE; ++i)
	{
		if (strncmp(str[i], "astro", 5) == 0)
		{
			printf("Found: %s\n", str[i]);
		}
	}
	
	return 0;
}

Operation results:

strcpy() and strncpy() functions

If you want to copy the entire string, use the strcpy() function, which is equivalent to the string assignment operator.

Example:

#include<stdio.h>
#include<string.h>
#define SIZE 40
int main(void)
{
	char str1[SIZE];
	char str2[SIZE] = { "I wanna be a programmer." };
	strcpy_s(str1, str2);
	puts(str1);
	return 0;
}

Operation results:

Other properties of strcpy()

  • The return type of strcpy() is char *, and the function returns the value of the first parameter, that is, the address of the first character.
  • The first argument does not have to point to the beginning of the array.

Example:

#include<stdio.h>
#include<string.h>
#define SIZE 50
int main(void)
{
	char str1[SIZE] = "I wanna be ";
	char str2[SIZE] = "a C programmer.";
	char* ptr;

	ptr = strcpy_s(str1 + 4, str2);
	puts(ptr);
	return 0;
}

But my compiler VS2019 doesn't seem to support this..

strncpy() function

Copying strings is safer with this function. The third parameter of the function indicates the maximum number of characters that can be copied.

Format:

strncpy(target, source, n);

Example:

#include<stdio.h>
#include<string.h>
#define SIZE 40
int main(void)
{
	char str1[SIZE];
	char str2[SIZE] = "He is a handsome man.";
	strncpy_s(str1, str2, 9);

	puts(str1);
	return 0;
}

Operation results:

sprintf() function

This function is declared in stdio H, unlike the printf() function, it writes data to a string instead of printing on the display.
Therefore, the function can combine multiple elements into a string.
The first parameter of the sprintf() function is the address of the target string, and the other parameters are the same as printf().

Example:

#include<stdio.h>
#include<assert.h>
#include<string.h>
#define LEN 20
#define SIZE 50
char* s_gets(char* st, int n);

int main(void)
{
	char first[LEN];
	char last[LEN];
	char formal[SIZE];
	double prize;

	puts("Please input your first name:");
	s_gets(first, LEN);
	puts("Please input your last name:");
	s_gets(last, LEN);
	puts("Enter your prize money");

	scanf_s("%lf", &prize);
	sprintf_s(formal, "%s, %-12s: $%6.2f\n", last, first, prize);
	puts(formal);
	return 0;
}

char* s_gets(char* st, int n)
{
	assert(st != nullptr);
	char* ret_val = fgets(st, n, stdin);
	int i = 0;
	if (ret_val)
	{
		while (st[i] != '\0' && st[i] != '\n')
			++i;
		if (st[i] == '\n')
			st[i] = '\0';
		else
			while (getchar() != '\n')
				continue;
	}
	return ret_val;
}

Operation results:

Other string functions

Some common strings:

char* strchr(const char* s, int c);

If the s string contains a c character, the function returns a pointer to the C character that first appears in the s string.; Null pointer if not found.

char* strrchr(const char*s, char c);

This function returns the position of the last occurrence of the c character in the s string (the null character at the end is also part of the string and is within the search range). If it is not found, it returns a null pointer.

char* strpbrk(const char* str1, const char* str2);

If the string str1 contains any character in the s2 string, the function returns a pointer to the first position of the s1 string; Null pointer if not included.

char* strstr(const char*str1, const char* str2);

This function returns a pointer to the first position of the str2 string in the str1 string. If not found in s1, a null pointer is returned.

Topics: C