一直做的是單片機相關的程序設計,所以程序設計上更偏向底層,對於字符串的操作也僅限於液晶屏幕上的顯示等工作,想提高下字符串操作的水平,而不是笨拙的數組替換等方式,翻看帖子發現C語言的字符串操作函數竟然這樣豐富而實用,在此記錄,已備后用。
No.1 strlen():字符串長度計算函數
應用實例:
1 #include<stdio.h>
2 #include<string.h>
3
4 char TextBuff[] = "Hello_My_Friend!"; 5
6 int main(void) 7 { 8 printf("TextBuff的長度是:%d\r\n",strlen(TextBuff)); 9 }
No.2 strcpy():字符串拷貝函數
應用實例:
1 #include<stdio.h>
2 #include<string.h>
3
4 char *TextBuff= "Hello_My_Friend!"; 5 char RevBuff[13]; 6
7 int main(void) 8 { 9 strcpy(RevBuff,TextBuff); 10 printf("RevBuff:%s\r\n",RevBuff); 11 }
No.3 strcat():字符串拼接函數
應用實例:
1 #include<stdio.h>
2 #include<string.h>
3
4 int main(void) 5 { 6 char *TextBuff; 7 char *A="IamA"; 8 char *B="IamB"; 9 char *C="IamC"; 10 strcat(TextBuff,A); 11 strcat(TextBuff,B); 12 strcat(TextBuff,C); 13 printf("TextBuff的長度是:%d\n",strlen(TextBuff)); 14 printf("%s\n",TextBuff); 15 }
No.4 strchr():字符串查找(第一次出現的位置)
應用實例:
1 #include<stdio.h>
2 #include<string.h>
3
4 int main(void) 5 { 6 char Text[10]="wearetheAB"; 7 char *Ptr; 8 char a='a'; 9
10 Ptr=strchr(Text,a); 11 printf("a的位置在Text的第%d個位置\n",Ptr-Text+1); 12 }
No.5 strcmp():字符串比較函數
應用實例:
1 #include<stdio.h>
2 #include<string.h>
3
4 int main(void) 5 { 6 char *A="Hello!"; 7 char *B="Hello!"; 8 char Num=0; 9 Num=strcmp(A,B); 10 if(Num==0) 11 { 12 printf("兩個數組相等\n"); 13 } 14 else
15 { 16 printf("兩個數組不相等\n"); 17 } 18 }
