1. 程式人生 > >C語言(C++)字串操作總結

C語言(C++)字串操作總結

1)字串讀入

第一種方式:

scanf("%s",str);

這種方式,是直接用 scanf,這樣讀字串的話,是從第一個字元讀起,然後讀至 空格、製表符、換行符 停止,是最簡單的方法,也比較常用。

 

第二種方式:

gets(str);

這種讀入方法,是會吃整行的字元,遇到 換行符 停止。

一般用於整行讀入,或者讀入含空格的字串。

注意:gets() 雖然不吃行尾的換行符,但是有可能會吃掉行首的換行符哦!

解決方法:gets() 前面加上 "getchar()" 即可。

 

第三種方式:

getline(str);

這種方式直接讀入一行,也不吃行首行尾的換行符哦!

 

 

2)字串操作 

複製字串:

strcpy(p, p1);

strcpy(char destination[], char source[]); 

功能:將字串 source (p) 拷貝到字串 destination (p1) 中,會覆蓋掉原來的字串。

 

複製指定長度字串 :

strncpy(p, p1, n);

strncpy(char destination[], char source[], int numchars);

功能:將字串 source (p1) 中前 numchars (n)

個字元拷貝到字串 destination (p) 中,同樣覆蓋原來字串。

 

附加字串 :

strcat(p, p1);

strcat(char target[], char source[]); 

功能:將字串 source (p1) 接到字串 target (p) 的後面 ,不會覆蓋原字串。

 

附加指定長度字串:

strncat(p, p1, n);

strncat(char target[], char source[], int numchars);

功能:將字串 source (p1) 的前 numchars (n)

個字元接到字串 target (p) 的後面 。

 

取字串長度:

strlen(p);

int n = strlen( char string[] );

功能:統計字串 string 中字元的個數 ,n 就是字串長度

 

比較字串:

strcmp(p, p1); 

int n=strcmp ( char firststring[], char secondstring);

功能:比較兩個字串 firststring (p)secondstring (p1)

如果 n > 0,說明在某一個地方,最先出現了 p[ i ] > p1[ i ]

如果 n < 0,說明在某一個地方,最先出現了 p[ i ] < p1[ i ]

如果 n = 0,說明這兩個字串完全一樣;

 

查詢字串:

strstr(p, p1);

char *p = strstr( char *string, char *strSearch);

在字串 string 中查詢 strSearch 子串.  返回子串 strSearchstring 中首次出現位置的指標. 如果沒有找到子串 strSearch , 則返回 NULL . 如果子串 strSearch 為空串, 函式返回 string 值。

 

OVER!