linux c常用字符串處理函數

 

一、puts

名稱:

puts

功能: 

向顯示器輸出字符串。

頭文件:

#include <stdio.h>

函數原形:

int puts(const char *s);

參數: 

s    字符串   

返回值: 

成功返回輸出的字符數,失敗返回EOF

put函數與printf函數在字符串輸出中的區別:

puts在輸出字符串時,遇到'\0'會自動終止輸出,並將'\0'轉換爲'\n'來輸出。

Printf在輸出字符串時,遇到'\0'只是終止輸出,並不會將'\0'轉換爲'\n'來輸出。

二、strcat

名稱:

strcat

功能: 

字符串連接函數

頭文件:

#include <string.h>

函數原形:

char *strcat(char *restrict s1,const char *restrict s2);

參數: 

s1    字符串1

s2    字符串2

返回值: 

返回字符數組1的首地址

Strcat能夠將字符串2連接到字符串1的後面。要注意的是字符串1必須能夠裝下字符串2。連接前,兩串均以'\0'結束,連接後,串1的'\0'被取消,新串最後加‘'\0'

如:

char name[100]="Mike";

char number[20]="001";

strcat(name,number);

puts(name);

輸出爲:

Mike001

三、strcpy

名稱:

strcpy

功能: 

字符串拷貝函數

頭文件:

#include <string.h>

函數原形:

char *strcpy(char *restrict s1,const char *restrict s2);

參數: 

s1    字符串1

s2    字符串2

返回值: 

返回字符數組1的首地址

strcpy將字符串2,拷貝到字符數組1中去,要注意,字符數組1必須足夠大,拷貝時'\0'一同拷貝,不能使用賦值語句爲一個字符數組賦值。

四、strcmp

名稱:

strcmp

功能: 

字符串比較函數

頭文件:

#include <string.h>

函數原形:

char *strcmp(const char *s1,const char *s2);

參數: 

s1    字符串1

s2    字符串2

返回值: 

返回int型整數

strcmp對兩串從左向右逐個字符比較(ASCLL嗎),直到遇到不同字符或'\0'爲止。若s1大於s2返回正整數,若s1小於s2返回負整數,若s1等於s2返回0。要注意字符串比較不能用"= =",必須用strcmp.

#include <stdio.h>

#include <string.h>

typedef struct

{

    char name[20];

    char num[20];

}USERINFO;

main()

{

    USERINFO user;

    char newname[ ]="Rose";

    int result;

    strcpy(user.name,"Mike");

    result=strcmp(user.name,newname);

    if(result!=0)

        printf("different person!");

    else

        Printf("the same person!");

五、strlen

名稱:

strlen

功能: 

字符串長度函數

頭文件:

#include <string.h>

函數原形:

int strlen(const char *s);

參數: 

s    字符串

返回值: 

返回字符串實際長度

strlen計算字符串長度並返回,不包含'\0'在內。

如:char str[100]="study";

int length;

length=strlen(str);

printf("%d",length);

輸出:5

六、strtok

名稱:

strtok

功能: 

字符串分割函數

頭文件:

#include <string.h>

函數原形:

char *strtok(char *s,const char *delim)

參數: 

s      欲分割的字符串

delim  分割字符串

返回值: 

返回下一個分割後的字符串指針,如果已無從分割則返回NULL

Strtok可將字符串分割,當strtok在參數s的字符串中發現到參數delim的分割字符時則會將該字符改爲\0字符。

在第一次調用時,strtok必須給予參數s字符串,往後的調用則將參數s設置爲NULL.

下面是程序例子:

#include <stdio.h> #include <string.h>

main()

{

    char s[ ]="ab-cd:de;gh:mnpe;ger-tu";

    char *delim="-:";

    char *p;

        printf("%s\n",strtok(s,delim));

    p=strtok(NULL,delim);

    while((p=strtok(NULL,delim)))

        Printf("%s\n",p);

}

輸出結果爲:

ab

cd

ee;gh

mnpe;ger

tu

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章