字符串是一种重要的数据类型,编写的任何应用程序,只要使用文本数据、或者与用户进行交互,都离不开对字符串的处理。C语言提供了一组字符串操作函数,方便开发者对字符串进行操作,函数原型在标准函数库<string.h>文件内。获取字符串的长度
用于获取字符串的长度,即字符串包含的有效字符个数(不包含结束符‘\0’),函数原型为:unsigned int strlen(char *s);函数返回字符数组s包含的有效字符个数,s为指向字符数组的指针。include <stdio.h>
#include <string.h>
int main() {
char exampleString[] = "Hello, World!";
size_t length = strlen(exampleString);
printf("The length of the string \"%s\" is: %d\n", exampleString, length);
return 0;
}
在案例代码中,strlen函数被用来计算exampleString的长度,并将结果存储在length变量中。然后使用printf函数输出字符串和它的长度。注意,strlen返回的是size_t类型的值,这是一个无符号整数类型,通常用于表示对象的大小。字符串的比较
用于比较两个字符串并根据比较结果返回一个整数,函数原型为:int strcmp ( const char * str1, const char * str2 );函数开始比较str1和str2的第一个字符,如果它们彼此相等,则继续比较后续字符,直到字符不同或到达str1或str2的结束符。#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
char str3[] = "Hello";
int result1 = strcmp(str1, str2);
int result2 = strcmp(str1, str3);
printf("strcmp(\"%s\", \"%s\") = %d\n", str1, str2, result1);
printf("strcmp(\"%s\", \"%s\") = %d\n", str1, str3, result2);
return 0;
}
strcmp("Hello", "World") = -1strcmp("Hello", "Hello") = 0strcmp函数对大小写敏感,因此"Hello"和"hello"是不同的。函数比较的是字符串的内容,而不是字符串的指针或地址。如果s1和s2中有一个是空指针(NULL),则strcmp函数的行为是未定义的,通常会导致程序崩溃。strcmp函数按照字符的ASCII值进行比较。查找子串
用于查找字符串是否包含指定的子串,子串就是字符串中一组任意连续的字符。函数原型为:char * strstr ( char * str1, const char * str2 );函数返回指向str1中第一个出现的str2的指针,如果str2不是str1的一部分,则返回空指针(即指针值为0)。#include <stdio.h>
#include <string.h>
int main() {
const char *str1 = "Hello, world!";
const char *str2 = "world";
char *result;
result = strstr(str1, str2);
if (result != NULL) {
printf("Found '%s' in '%s' at position: %ld\n", str2, str1, result - str1);
} else {
printf("'%s' not found in '%s'\n", str2, str1);
}
return 0;
}
案例代码会在 str1 中查找 str2,并打印出 str2 在 str1 中首次出现的位置(从 str1 的开始位置计算)。
Strstr()函数对大小写敏感。例如:"Hello, World!" 中找不到 "world",因为大小写不匹配。strstr 返回的是指向 str1 中字符串的指针,而不是一个新的字符串,返回的指针实际上是指向 str1 的内存地址。字符串的连接
用于连接两个字符串,两个字符串合并为一个字符串,函数原型为:char * strcat ( char * destination, const char * source );函数将source的副本附加到destination字符串的尾部 ,destination的结束符被source的第一个字符覆盖。函数返回destination。#include <stdio.h>
#include <string.h>
int main() {
char dest[50] = "Hello, ";
const char *src = "World!";
strcat(dest, src);
printf("%s\n", dest);
return 0;
}
使用strcat()函数连接字符串时,需要注意缓冲区是否溢出,strcat不会自动检查目标字符串是否有足够的空间来容纳源字符串。如果目标字符串的空间不足以容纳两个字符串的总和,就会发生缓冲区溢出。字符串分割
用于分解字符串,它主要用于将一个字符串按照指定的分隔符进行分割,生成一系列的子字符串。char *strtok(char *str, const char *delim);str:要进行分解的字符串。第一次调用 strtok 时,str应该是原始字符串。之后的调用,str应该是 NULL,因为 strtok 会在内部保存其状态,以便进行连续的分解操作。delim:指定分隔符的字符串,strtok 会使用delim来分割原始字符串。strtok 函数会修改原始字符串,通过插入空字符(\0)来分隔子字符串。因此在分解原始字符串之前,最好将原始字符串复制一份。#include <stdio.h>
#include <string.h>
int main() {
char str[] = "This,is,a,test";
char *token;
token = strtok(str, ",");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, ",");
}
return 0;
}