字符串连接
编写一个程序,从键盘输入两个字符串,分别求出这两个字符串长度,并输出字符串和长度值,将第二个字符串连接到第一个的尾部,再求出连接后得到的新串的长度,并输出新字符串和长度值
解题思路: 求字符串长度可以用库函数string.h中的strlen函数,连接两个字符串可以使用库函数string.h中的strcat函数,当然也可以自己来写这两个函数来实现这个功能
借用库函数的代码如下:
1 #include <stdio.h> 2 #include <string.h> 3 4 int main() 5 { 6 int n1, n2, n3; 7 char s1[100], s2[100]; 8 scanf("%s",&s1); 9 scanf("%s",&s2); 10 n1 = strlen(s1); 11 n2 = strlen(s2); 12 printf("第一个字符串的长度为%d,第二个字符串的长度为%d\n",n1,n2); 13 strcat(s1, s2); 14 n3 = strlen(s1); 15 printf("新字符串为%s,其长度为%d\n",s1,n3); 16 return 0; 17 }
自己写的函数来实现求字符串长度和字符串连接代码如下:
1 #include <stdio.h> 2 3 int Strlen(char *s) //求字符串的长度 4 { 5 int n=0; 6 char *p = s; 7 while(*p) 8 { 9 n++; 10 p++; 11 } 12 return n; 13 } 14 15 //连接时注意连接完后在s1后面加上结束标志'\0' 16 char* Strcat(char *s1, char *s2) //把s2连接到s1后面 17 { 18 char *p1 = s1, *p2 = s2; 19 while(*p1) 20 { 21 p1++; 22 } 23 while(*p2) 24 { 25 *p1 = *p2; 26 p1++; 27 p2++; 28 } 29 *p1 = '\0'; 30 return p1; 31 } 32 33 int main() 34 { 35 int n1, n2, n3; 36 char s1[100], s2[100]; 37 scanf("%s",&s1); 38 scanf("%s",&s2); 39 n1 = Strlen(s1); 40 n2 = Strlen(s2); 41 printf("第一个字符串的长度为%d,第二个字符串的长度为%d\n",n1,n2); 42 Strcat(s1, s2); 43 n3 = Strlen(s1); 44 printf("新字符串为%s,其长度为%d\n",s1,n3); 45 46 return 0; 47 }
too young too simple sometimes native!

浙公网安备 33010602011771号