在C语言中,字符串是以字符数组的形式存在的,而标准库提供了一系列用于操作字符串的函数,这些函数被定义在`
1. strlen() - 计算字符串长度
`strlen()`函数用于计算字符串的长度,即从字符串起始位置到第一个'\0'之间的字符数量。需要注意的是,它不会统计终止符'\0'本身。
```c
include
include
int main() {
char str[] = "Hello, World!";
printf("Length of string: %lu\n", strlen(str));
return 0;
}
```
2. strcpy() - 复制字符串
`strcpy()`函数用于将一个字符串复制到另一个字符串中。目标字符串必须有足够的空间来存储源字符串。
```c
include
include
int main() {
char src[] = "Source String";
char dest[50];
strcpy(dest, src);
printf("Copied string: %s\n", dest);
return 0;
}
```
3. strcat() - 连接字符串
`strcat()`函数用于将一个字符串追加到另一个字符串的末尾。与`strcpy()`类似,目标字符串需要有足够的空间容纳连接后的结果。
```c
include
include
int main() {
char str1[50] = "Hello, ";
char str2[] = "World!";
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
return 0;
}
```
4. strcmp() - 比较字符串
`strcmp()`函数用于比较两个字符串。如果返回值为0,则表示两个字符串相等;若小于0,则第一个字符串小于第二个字符串;若大于0,则第一个字符串大于第二个字符串。
```c
include
include
int main() {
char str1[] = "Apple";
char str2[] = "Banana";
if (strcmp(str1, str2) == 0)
printf("Strings are equal.\n");
else
printf("Strings are not equal.\n");
return 0;
}
```
5. strchr() - 查找字符
`strchr()`函数用于查找某个字符在字符串中的首次出现位置。如果找到该字符,返回指向该字符的指针;否则返回NULL。
```c
include
include
int main() {
char str[] = "Search this string.";
char ptr = strchr(str, 'h');
if (ptr != NULL)
printf("Character found at position: %ld\n", ptr - str + 1);
else
printf("Character not found.\n");
return 0;
}
```
6. strstr() - 查找子字符串
`strstr()`函数用于查找子字符串在主字符串中的首次出现位置。如果找到子字符串,返回指向该子字符串的指针;否则返回NULL。
```c
include
include
int main() {
char str[] = "Find substring in this string.";
char sub[] = "substring";
char ptr = strstr(str, sub);
if (ptr != NULL)
printf("Substring found at position: %ld\n", ptr - str + 1);
else
printf("Substring not found.\n");
return 0;
}
```
总结
以上是C语言中一些常用字符串操作函数的简要介绍。通过合理使用这些函数,可以高效地进行字符串处理,从而简化编程任务。希望本文能帮助您更好地理解和应用这些重要的工具。