#include <stdio.h> #include <string.h>/*頭文件*/ void main() { char s1[100],s2[50]; printf("Enter the first string:\n"); gets(s1); /*運用gets()函數進行輸入*/ printf("Enter the second string:\n"); gets(s2); strcat(s1,s2); puts(s1); /*運用puts()函數進行輸出*/ char str1[20] = {"how do you do"}, str2[] = {"How are you!"}; strcpy(str1,str2); puts(str1); }
輸出函數puts()和gets()函數比printf和scanf的好處在於不用過多考慮格式化問題。函數
#include <stdio.h> #include <string.h> void main() { char str1[20] = {"how do you do"}, str2[] = {"How are you!"}; strcpy(str1,str2);/*字符串拷貝*/ puts(str1); }
字符串比較函數strcmp()、求字符串長度函數strlen()code
#include <stdio.h> #include <string.h> void main() { int a, b, c; char str1[]={"hello"}, str2[]={"how are you!"}; a = strcmp(str1,str2); b = strcmp("Chinese","China"); c = strcmp(str1,"how"); printf("%d,%d,%d",a,b,c);/*按ASCII碼比較,若是str1大於str2,輸出1,若是str1等於str2,輸出0;若是str小於str2,輸出-1.*/ printf("%d\n",strlen(str1));/*輸出字符串str1的長度*/ printf("%d\n",strlen(str2));/*輸出字符串str2的長度*/ }