C语言字符串
字符串是字符数组,并以空字符(\0)结尾。用户不会放置空字符,编译器会自动将其放置在字符串的末尾。
数组和字符串之间的区别在于,编译器不会在数组末尾放置空字符,而在字符串中,编译器会放置空字符。
这是C语言中string的语法,
char myStr[size];
这里,
myStr:字符串
大小:设置字符串的大小
用C语言初始化字符串,如下所示-
char myStr[size] = “string”;
char myStr[size] = { ‘s’,’t’,’r’,’i’,’n’,’g’,’\0’ };下表显示了C语言中的字符串功能。
这是C语言中的字符串示例,
示例
#include <stdio.h>
#include <string.h>
int main () {
char s1[10] = "Hello";
char s2[10] = "World";
int len, com ;
strcpy(s1, s2);
printf("Strings s1 and s2 : %s\t%s\n", s1, s2 );
strcat( s1, s2);
printf("String concatenation: %s\n", s1 );
len = strlen(s1);
printf("Length of string s1 : %d\n", len );
com = strcmp(s1,s2);
printf("Comparison of strings s1 and s2 : %d\n", com );
return 0;
}输出结果
Strings s1 and s2 : WorldWorld String concatenation: WorldWorld Length of string s1 : 10 Comparison of strings s1 and s2 : 87