在C语言中字符串是一个字符数组。
声明字符串:
#include <stdlib.h>
int main(int argc, char* argv[])
{
char str1[] = {'h', 'e', 'l', 'l', 'o', '\0'};
char str2[] = "hello"; //自动添加终止符'\0'
printf("%s\n%s\n", str1, str2);
system("pause");
return 0;
}
读取和输出字符串:
#include <stdlib.h>
//方法一:使用scanf、printf
int main(int argc, char* argv[])
{
char first_name[20];
printf("Enter your firstname:");
scanf("%s", first_name);
printf("%s\n", first_name);
system("pause");
return 0;
}
#include <stdlib.h>
//方法二:使用gets、puts
int main(int argc, char* argv[])
{
char first_name[20];
puts("Enter your firstname:");
gets(first_name);
puts(first_name);
system("pause");
return 0;
}
要对字符串长度计算、字符串连接、复制等功能,则需要使用标准库中预置的函数。这些函数存放在头文件string.h中。
1.字符串长度函数strlen
size_t strlen(const char *str)
size_t 表示无符号短整数,它返回字符串的长度而不包括终止字符'\0'
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
char str1[20] = "hello";
printf("Length of string str1: %d\n", strlen(str1)); //5
system("pause");
return 0;
}
strlen和sizeof
strlen返回存储在数组中的字符串的长度,sizeof返回分配给数组的总大小
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
char str1[20] = "hello";
printf("strlen=%d\nsizeof=%d\n", strlen(str1), sizeof(str1));
//strlen=5
//sizeof=20
system("pause");
return 0;
}
2.字符串比较函数strcmp
int strcmp(const char *str1, const char *str2)
比较两个字符串并返回一个整数值。如果两个字符串相同(相等),则此函数将返回 0,不相等返回非 0。
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
char str1[20] = "hello";
char str2[20] = "world";
printf("%d\n", strcmp(str1, str2));
system("pause");
return 0;
}
3.字符串连接函数strcat
char *strcat(char *str1, char *str2)
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
char str1[20] = "hello";
char str2[20] = "world";
strcat(str1, str2);
printf("%s\n", str1);//helloworld
printf("%s\n", str2);//world
system("pause");
return 0;
}
4.字符串复制函数strcpy
char *strcpy( char *str1, char *str2)
它将字符串str2复制到字符串str1中,包括终止字符'\0'
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
char str1[20] = "hello";
char str2[20] = "world";
strcpy(str1, str2);
printf("%s\n", str1);//world
printf("%s\n", str2);//world
system("pause");
return 0;
}
5.在字符串中查找字符strchr
char *strchr(char *str, int ch)
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
char str1[20] = "hello";
printf("%s\n", strchr(str1, 'o'));
system("pause");
return 0;
}