后端
C语言字符串处理
C语言字符串处理
strlen():计算字符串长度
- 语法格式:
size_t strlen(const char *s); - 示例:
int len = strlen("Hello"); // len = 5
- 语法格式:
strcpy():复制字符串
- 语法格式:
char *strcpy(char *dest, const char *src); - 示例:
strcpy(dest, "Hello");
- 语法格式:
strcmp():比较两个字符串
- 语法格式:
int strcmp(const char *s1, const char *s2); - 示例:
int result = strcmp("apple", "banana"); // result < 0
- 语法格式:
strcat():连接两个字符串
- 语法格式:
char *strcat(char *dest, const char *src); - 示例:
strcat(dest, " World");
- 语法格式:
sprintf():格式化输出到字符串
- 语法格式:
int sprintf(char *str, const char *format, ...); - 示例:
sprintf(str, "Age: %d", 25);
- 语法格式:
strncpy():复制指定长度的字符串
- 语法格式:
char *strncpy(char *dest, const char *src, size_t n); - 示例:
strncpy(dest, src, 10);
- 语法格式:
strstr():查找子字符串
- 语法格式:
char *strstr(const char *haystack, const char *needle); - 示例:
char *pos = strstr("Hello World", "World");
- 语法格式:
strchr():查找字符在字符串中的位置
- 语法格式:
char *strchr(const char *s, int c); - 示例:
char *pos = strchr("Hello", 'l');
- 语法格式:
字符串处理示例
c
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello";
char str2[50] = "World";
char result[100];
int length, compare;
// 计算字符串长度
length = strlen(str1);
printf("Length of str1: %d\n", length);
// 复制字符串
strcpy(result, str1);
printf("Copied string: %s\n", result);
// 连接字符串
strcat(result, " ");
strcat(result, str2);
printf("Concatenated string: %s\n", result);
// 比较字符串
compare = strcmp(str1, str2);
if (compare < 0) {
printf("%s comes before %s\n", str1, str2);
} else if (compare > 0) {
printf("%s comes after %s\n", str1, str2);
} else {
printf("%s is equal to %s\n", str1, str2);
}
// 格式化输出到字符串
sprintf(result, "%s %s - Length: %d", str1, str2, length);
printf("Formatted string: %s\n", result);
// 查找子字符串
char *pos = strstr(result, "World");
if (pos) {
printf("Found 'World' at position: %d\n", pos - result);
}
return 0;
}输出结果
Length of str1: 5
Copied string: Hello
Concatenated string: Hello World
Hello comes before World
Formatted string: Hello World - Length: 5
Found 'World' at position: 6