C語(yǔ)言編程常見問題解答之字符串操作

字號(hào):

本章集中討論字符串操作,包括拷貝字符串,拷貝字符串的一部分,比較字符串,字符串右對(duì)齊,刪去字符串前后的空格,轉(zhuǎn)換字符串,等等。C語(yǔ)言提供了許多用來處理字符串的標(biāo)準(zhǔn)庫(kù)函數(shù),本章將介紹其中的一部分函數(shù)。
     在編寫C程序時(shí),經(jīng)常要用到處理字符串的技巧,本章提供的例子將幫助你快速學(xué)會(huì)一些常用函數(shù)的使用方法,其中的許多例子還能有效地幫助你節(jié)省編寫程序的時(shí)間。
     6.1 串拷貝(strcpy)和內(nèi)存拷貝(memcpy)有什么不同?它們適合于在哪種情況下使用?
     strcpy()函數(shù)只能拷貝字符串。strcpy()函數(shù)將源字符串的每個(gè)字節(jié)拷貝到目錄字符串中,當(dāng)遇到字符串末尾的null字符(\0)時(shí),它會(huì)刪去該字符,并結(jié)束拷貝。
     memcpy()函數(shù)可以拷貝任意類型的數(shù)據(jù)。因?yàn)椴⒉皇撬械臄?shù)據(jù)都以null字符結(jié)束,所以你要為memcpy()函數(shù)指定要拷貝的字節(jié)數(shù)。
     在拷貝字符串時(shí),通常都使用strcpy()函數(shù);在拷貝其它數(shù)據(jù)(例如結(jié)構(gòu))時(shí),通常都使用memcpy()函數(shù)。
     以下是一個(gè)使用strcpy()函數(shù)和memcpy()函數(shù)的例子:
    #include
    #include
    typedef struct cust-str {
     int id ;
     char last_name [20] ;
     char first_name[l5];
    } CUSTREC;
    void main (void);
    void main (void)
    {
     char * src_string = "This is the source string" ;
     char dest_string[50];
     CUSTREC src_cust;
     CUSTREC dest_cust;
     printf("Hello! I’m going to copy src_string into dest_string!\n");
     / * Copy src_ string into dest-string. Notice that the destination
     string is the first argument. Notice also that the strcpy()
     function returns a pointer to the destination string. * /
     printf("Done! dest_string is: %s\n" ,
     strcpy(dest_string, src_string)) ;
     printf("Encore! Let’s copy one CUSTREC to another. \n") ;
     prinft("I’ll copy src_cust into dest_cust. \n");
     / * First, intialize the src_cust data members. * /
     src_cust. id = 1 ;
     strcpy(src_cust. last_name, "Strahan");
     strcpy(src_cust. first_name, "Troy");
     / * Now, Use the memcpy() function to copy the src-cust structure to
     the dest_cust structure. Notice that, just as with strcpy(), the
     destination comes first. * /
     memcpy(&dest_cust, &src_cust, sizeof(CUSTREC));
     printf("Done! I just copied customer number # %d (%s %s). " ,
     dest_cust. id, dest_cust. first_name, dest_cust. last_name) ;
    }
     請(qǐng)參見:
     6.6怎樣拷貝字符串的一部分?
     6.7怎樣打印字符串的一部分?
     6. 2怎樣刪去字符串尾部的空格?。
     C語(yǔ)言沒有提供可刪去字符串尾部空格的標(biāo)準(zhǔn)庫(kù)函數(shù),但是,編寫這樣的一個(gè)函數(shù)是很方便的。請(qǐng)看下例:
    #include
    # include
    void main (void);
    char * rtrim(char * );
    void main(void)
    {
     char * trail_str = "This string has trailing spaces in it";