How to use strings in the C language?
In C language, string represents a collection of characters. There is no native string type in C language, instead, character arrays are used to represent strings. Here are some common string manipulation methods:
- Declare a string variable: You can declare a string variable using a character array, for example: char str[100];
- Initialize the string: you can use string constants to do so, for example: char str[100] = “Hello, World”;
- To obtain the length of a string: You can use the strlen() function to get the length of a string, for example: int len = strlen(str);
- Concatenate two strings: You can use the strcat() function to concatenate two strings, for example: strcat(str1, str2);
- Compare strings: The strcmp() function can be used to compare two strings. The return value is 0 if the strings are equal, greater than 0 if str1 is greater than str2, and less than 0 if str1 is less than str2. For example: int result = strcmp(str1, str2);
- Copy a string: You can use the strcpy() function to copy a string, for example: strcpy(str1, str2);
- Searching for a substring: You can use the strstr() function to find the position of a substring within a string, for example: char *pos = strstr(str, “World”);
- Format output string: You can use the printf() function to format output strings, for example: printf(“Hello, %s”, name);
These are some common string manipulation methods. In C language, there are many other string manipulation functions available. You can choose the appropriate function based on your specific needs.