1. 程式人生 > >C語言中對字串的操

C語言中對字串的操

最近對於C語言接收到的資料(字串)處理比較多。

字串:零個或多個字元組成的有限序列。假設:S="abcd1234efghmn",其中S是串列埠,字串中的字元可以是字元、數字或其他字元。

#include <string.h>

#include <stdio.h>

C ANSI 對於C的操作有

複製字串

char *strcpy(char* dest, const char *src);//把從str地址開始包含有NULL(\0)結束符的字串複製到dest開始的地址空間

char* strncpy(char* dest,char *src,size_t n); //把從str地址開始前n個字元(不含NULL)字元(n<sizeof(src)

字串長度

unsigned int strlen(char *s); //計算給定字串的長度,不包括'\0'在內。

從字串中查詢指定字元

char *strchr(const char *s,char c); 字串s中首次出現字元c的地址---正向

char *strrchr(const char *str, char c);字串s中首次出現字元c的地址---反向

從字串中查詢子串

char *strstr(char *str1, const char *str2);//若str2是str1的子串,則返回str2在str1的首次出現的地址;如果str2不是str1的子串,則返回NULL。

附加子串到目標字串

 char *strcat(char *dest, const char *src);

char * strcat(char *dest, const char *str,size_t n);

比較字串

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


字串到數值型別的轉換

int atoi(const char *nptr);  //字串轉換成整數

double atof(const char *nptr);//字串轉換成浮點數

long atof(const char *nptr); //字串轉換成長整數


double strtod(const char *nptr, char **endptr);  //將字串裝換成浮點數,會掃描引數nptr字串,跳過前面的空格字元,直到遇到數字或正負符號才開始做轉換,到出現非數字或字串結束時('\0')才結束轉換,並將結果返回。


舉個栗子:

{

char buf[] = "http://www.fangle.com/postedit/emmidt:80"

char PA=NULL;

char PB=NULL;

        char PC=NULL;

int port = 0;

char host[128] = {0};

PA = buf;

if(!strncmp(PA,"http://",strlen("http://")))

PA = buf+strlen("http://");

PB = strchr(PA,':');

if(PB)

port = *atoi(PB+1);

else

prot = 80;

memcpy(host, PA, strlen(PA)-strlen(PB));

host[ strlen(PA)-strlen(PB)] = ‘\0’;

}

對比strcpy和memcpy

函式void * memcpy(const void *dest, const void *src, size_t size)

src指向記憶體塊的資料拷貝size個數據到dest指向的記憶體塊.

即memcpy對於需要複製的內容沒有限制,因此用途更廣——一般記憶體的複製


char *strcpy(char * dest, const char *src) 實現src到dest的複製 遇到/0結束。