gets
獲取用戶從鍵盤輸入的字符串.
例子
#include <stdio.h>
int main(){
char str[100];
printf("Input Something: ");
gets(str);
puts(str);
return 0;
}
運行結(jié)果:
Input Something: Hello World
Hello World
當(dāng)輸入的字符串中含有空格時,輸出仍為全部字符串书释。說明 gets 函數(shù)并不以空格作為字符串輸入結(jié)束的標(biāo)志,而只以回車作為輸入結(jié)束.
strlen
將返回字符串的整數(shù)長度赊窥。
例子
#include <stdio.h>
#include <string.h>
int main(){
char str="hello world";
int len = strlen(str);
printf("The lenth of the string is %d\n", len);
return 0;
}
運行結(jié)果:
The lenth of the string is 11
需要說明:
- 要添加 #include<string.h>
- strlen 會從字符串的第 0 個字符開始計算爆惧,直到遇到字符串結(jié)束標(biāo)志 '\0'。
strcat
把兩個字符串拼接在一起
例子
#include <stdio.h>
#include <string.h>
int main(){
char str1[40]="welcome back ";
int str2[20];
printf("Input your name:");
gets(str2);
strcat(str1,str2);
puts(st1);
return 0;
}
運行結(jié)果:
Input your name:hejing
welcome back hejing
需要說明:
- strcat 將把 str2 連接到 str1后面锨能,并刪去 str1 最后的結(jié)束標(biāo)志 '\0'扯再。這就意味著,str1 的長度要足夠址遇,必須能夠同時容納 str1 和 str2熄阻,否則會越界.
- strcat 返回值為 str1 的首地址
**strcpy **
字符串復(fù)制
例子
#include <stdio.h>
#include <string.h>
int main(){
char str1[15], str2="C Language";
strcpy(str1, str2);
puts(str1);
printf("\n");
return 0;
}
運行結(jié)果:
C Language
需要說明
- strcpy 會把 str2中的字符串拷貝到 str1中,串結(jié)束標(biāo)志 '\0' 也一同拷貝倔约。
- 要求str1有足夠長度秃殉,否則不能全部裝入所拷貝的字符串。
strtok
分解字符串為一組標(biāo)記串浸剩。s為要分解的字符串钾军,delim為分隔符字符串。
例子
/* strtok example */
#include <stdio.h>
#include <string.h>
int main (void)
{
char str[] = "- This, a sample string.";
char *pch;
printf("Splitting string \"%s\" into tokens:\n", str);
pch = strtok(str," ,.-");
while (pch != NULL)
{
printf("%s\n", pch);
pch = strtok(NULL, " ,.-");
}
printf("at the end: %s", str);
return 0;
}
運行結(jié)果
Splitting string "- This, a sample string." into tokens:
This
a
sample
string
the end: - This
說明:strtok()用來將字符串分割成一個個片段绢要。當(dāng)strtok()在參數(shù)s的字符串中發(fā)現(xiàn)到參數(shù)delim的分割字符時則會將該字符改為 \0 字符吏恭。在第一次調(diào)用時,strtok()必需給予參數(shù)s字符串重罪,往后的調(diào)用則將參數(shù)s設(shè)置成NULL砸泛。每次調(diào)用成功則返回被分割出片段的指針。當(dāng)沒有被分割的串時則返回NULL蛆封。所有delim中包含的字符都會被濾掉,并將被濾掉的地方設(shè)為一處分割的節(jié)點勾栗。
strstr
從字符串 str1 中尋找 str2 第一次出現(xiàn)的位置(不比較結(jié)束符NULL)惨篱,如果沒找到則返回NULL。
例子
/* strstr example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "This is a simple string";
char *pch;
pch = strstr(str, "simple");
strncpy(pch, "sample", 7);
puts(pch);
puts(str);
return 0;
}
運行結(jié)果
sample string
This is a sample string
其他一些函數(shù)
strncpy
函數(shù)原型charstrncpy(chardest,char*src,size_tn);
復(fù)制字符串src中的內(nèi)容(字符围俘,數(shù)字砸讳、漢字....)到字符串dest中,復(fù)制多少由size_tn的值決定界牡。
strcmp
原型 int strcmp ( const char * str1, const char * str2 );
功能:比較字符串 str1 和 str2簿寂。
說明:
當(dāng)s1<s2時,返回值<0
當(dāng)s1=s2時宿亡,返回值=0
當(dāng)s1>s2時常遂,返回值>0
...