C語言字符串操作(轉)

 本章集中討論字符串操作,包括拷貝字符串,拷貝字符串的一部分,比較字符串,字符串右對齊,刪去字符串前後的空格,轉換字符串,等等。C語言提供了許多用來處理字符串的標準庫函數,本章將介紹其中的一部分函數。
    在編寫C程序時,經常要用到處理字符串的技巧,本章提供的例子將幫助你快速學會一些常用函數的使用方法,其中的許多例子還能有效地幫助你節省編寫程序的時間。

    6.1 串拷貝(strcpy)和內存拷貝(memcpy)有什麼不同?它們適合於在哪種情況下使用?
    strcpy()函數只能拷貝字符串。strcpy()函數將源字符串的每個字節拷貝到目錄字符串中,當遇到字符串末尾的null字符(/0)時,它會刪去該字符,並結束拷貝。
    memcpy()函數可以拷貝任意類型的數據。因爲並不是所有的數據都以null字符結束,所以你要爲memcpy()函數指定要拷貝的字節數。
      在拷貝字符串時,通常都使用strcpy()函數;在拷貝其它數據(例如結構)時,通常都使用memcpy()函數。
    以下是一個使用strcpy()函數和memcpy()函數的例子:

#include <stdio. h>
#include <string. h>
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) ;
}

請參見:   
    6.6怎樣拷貝字符串的一部分?
6.7怎樣打印字符串的一部分?

    6. 2怎樣刪去字符串尾部的空格?。
C語言沒有提供可刪去字符串尾部空格的標準庫函數,但是,編寫這樣的一個函數是很方便的。請看下例:
#include <stdio. h>
# include <string. h>

void main (void);
char * rtrim(char * );
void main(void)
{
    char * trail_str = "This string has trailing spaces in it";
   / * Show the status of the string before calling the rtrim()
       function. * /
    printf("Before calling rtrim(), trail_str is '%s'/fi" , trail_str);
    print ("and has a length of %d. /n" , strlen (trail_str));
   / * Call the rtrimO function to remove the trailing blanks. * /
    rtrim(trail_str) ;
   / * Show the status of the string
       after calling the rtrim() function. * /
    printf("After calling rttim(), trail_ str is '%s'/n", trail _ str );
    printf ("and has a length of %d. /n" , strlen(trail-str)) ;
}
/ * The rtrim() function removes trailing spaces from a string. * /.

char * rtrim(char * str)
{
    int n = strlen(str)-1; / * Start at the character BEFORE
                               the null character (/0). * /
    while (n>0) / * Make sure we don't go out of hounds. . . * /
    {
        if ( * (str + n) 1 =' ') / * If we find a nonspace character: * /
        {
            * (str+n+1) = '/0' ; / * Put the null character at one
                                     character past our current
                                     position. * /
            break ; / * Break out of the loop. * /
        }
        else / * Otherwise , keep moving backward in the string. * /.
            n--;
    }
    return str;    /*Return a pointer to the string*/
}

    在上例中,rtrim()是用戶編寫的一個函數,它可以刪去字符串尾部的空格。函數rtrim()從字符串中位於null字符前的那個字符開始往回檢查每 個字符,當遇到第一個不是空格的字符時,就將該字符後面的字符替換爲null字符。因爲在C語言中null字符是字符串的結束標誌,所以函數rtrim ()的作用實際上就是刪去字符串尾部的所有空格。

    請參見:   
    6.3怎樣刪去字符串頭部的空格?
    6.5怎樣將字符串打印成指定長度?
   
    6.3 怎樣刪去字符串頭部的空格?
    C語言沒有提供可刪去字符串頭部空格的標準庫函數,但是,編寫這樣的一個函數是很方便的。請看下例;
#include <stdio. h>
#include <string. h>

void main(void);
char * ltrim (char * ) ;
char * rtrim(char * ) ;
void main (void)
{
    char * lead_str = " This string has leading spaces in it. " ;,
    / * Show the status of the string before calling the Itrim()
        function. * /
    printf("Before calling Itrim(), lead-str is '%s'/n", lead_str);
    printf("and has a length of %d. /n" , strlen(lead_str));
    / * Call the Itrim() function to remove the leading blanks. * /.
        Itrim(lead_str);
    / * Show the status of the string
        after calling the Itrim() function. * /
    prinft("After calling Itrim(), lead_str is '%s'/n", lead_str);
    print("and has a length of %d. /n'' , strlen(lead-str)) ;
}
/ * The Itrim() function removes leading spaces from a string. * /

char * ltrim(char * str)
{
    strrev(str) ; / * Call strrevO to reverse the string. * /
    rtrim(str)). /* Call rtrimO to remvoe the "trailing" spaces. * /
    strrev(str); / * Restore the string's original order. * /
    return str ; / * Return a pointer to the string. * /.
}
/ * The rtrim() function removes trailing spaces from a string. * /

char* rtrim(char* str)
{
    int n = strlen (str)-l ; / * Start at the character BEFORE
    the null character (/0). * /
    while (n>0) / * Make sure we don't go out of bounds... * /.
    {
        if ( * (str+n) ! =' ') If we find a nonspace character: * /
        {
            * (str+n + 1) = '/0' ; / * Put the null character at one
            character past our current
            position. * /
            break;j / * Break out of the loop. * /
        }
        else / * Otherwise, keep moving backward in the string. * /
            n --;
    }
    return str;    /* Return a pointer tO the string. */
}

    在上例中,刪去字符串頭部空格的工作是由用戶編寫的ltrim()函數完成的,該函數調用了·6.2的例子中的rtrim()函數和標準C庫函數 strrev()。ltrim()函數首先調用strrev()函數將字符串顛倒一次,然後調用rtrim()函數刪去字符串尾部的空格,最後調用 strrev()函數將字符串再顛倒一次,其結果實際上就是刪去原字符串頭部的空格。

    請參見:
    6.2怎樣刪去字符串尾部的空格?   
    6.5怎樣將字符串打印成指定長度?

    6.4 怎樣使字符串右對齊?    
    C語言沒有提供可使字符串右對齊的標準庫函數,但是,編寫這樣的一個函數是很方便的。請看下例:
#include <stdio. h>
#include <string. h>
#include <malloc. h>

void main (void);
char * r just (char * ) ;
char * rtrim(char * );
void main (void)
{
    char * rjust_str = "This string is not righ-justified. " ;
    / * Show the status of the string before calling the rjust()
        function. * /
    printf("Before calling rjust(), rjust_str is ' %s'/n. " , rjust_str);
    / * Call the rjustO function to right-justify this string. * /
    rjust(rjust_str) ;
    / * Show the status of the string
        after calling the rjust() function. * /
    printf ("After calling rjust() , rjust_str is ' %s'/n. " , rjust_str) ;
}
/ * The rjust() function right-justifies a string. * /
char * r just (char * str)
{
    int n = strlen(str); / * Save the original length of the string. * /
    char* dup_str;
    dup_str = strdup(str); / * Make an exact duplicate of the string. * /
    rtrim(dup_str); /* Trim off the trailing spaces. */
    / * Call sprintf () to do a virtual "printf" back into the original
        string. By passing sprintf () the length of the original string,
        we force the output to be the same size as the original, and by
        default the sprintf() right-justifies the output. The sprintf()
        function fills the beginning of the string with spaces to make
        it the same size as the original string. * /

    sprintf(str, "%*. * s", n, n, dup_str);

    free(dup-str) ; / * Free the memory taken by
    the duplicated string. * /
    return str;/ / * Return a pointer to the string. * /
}

/ * The rtrim() function removes trailing spaces from a string. * /
char * rtrim(char * str)
{
    int n = strlen(str)-l; / * Start at the character BEFORE the null
                               character (/0). * /
    while (n>0) / * Make sure we don't go out of bounds... * /
    {
        if ( * (str+n) ! = ' ') / * If we find a nonspace character: * /
        {
            * (str + n + 1) = '/0';( / * Put the null character at one
                                         character past our current
                                         position. * /
             break; / * Break out of the loop. * /
        }
        else / * Otherwise, keep moving backward in the string. * /
            n—;
    }
    return str ; / * Return a pointer to the string. * /
}
  
   在上例中,使字符串右對齊的工作是由用戶編寫的rjust()函數完成的,該函數調用了6.2的例子中的rtrim()函數和幾個標準函數。rjust()函數的工作過程如下所示:
    (1) 將原字符串的長度存到變量n中。這一步是不可缺少的,因爲輸出字符串和原字符串的長度必須相同。
    (2) 調用標準C庫函數strdup(),將原字符串複製到dup_str中。原字符串需要有一份拷貝,因爲經過右對齊處理的字符串要寫到原字符串中。
    (3) 調用rtrim()函數,刪去dup_str尾部的空格。
    (4) 調用標準C庫函數sprinf(),將dup_str寫到原字符串中。由於原字符串的長度(存在n中)被傳遞給sprintf()函數,所以迫使輸出字符 串的長度和原字符串相同。因爲sprintf()函數缺省使輸出字符串右對齊,因此輸出字符串的頭部將被加入空格,以使它和原字符串長度相同,其效果實際 上就是使原字符串右對齊。
    (5)調用標準庫函數free(),釋放由strdup()函數分配給dup_str的動態內存。

    請參見:   
    6.5怎樣將字符串打印成指定長度?   

    6.5 怎樣將字符串打印成指定長度?   
    如果要按表格形式打印一組字符串,你就需要將字符串打印成指定長度。利用printf()函數可以很方便地實現這一點,請看下例:

# include <stdio. h>
char * data[25] = {
    "REGION", "--Q1--", "--Q2--", "--Q3--", "--Q4--",
    "North" , "10090. 50" , "12200. 10" , "26653.12" , "62634. 32" ,
    "South", "21662.37", "95843.23", "23788.23", "48279.28",
    "East", "23889.38", "23789.05", "89432.84", "29874.48",
    "West", "85933.82", "74373.23", "78457.23", "28799.84" };
void main (void) ;
void main (void)
{
    int x;
    fox (x = 0, x<25; x+ + )
    {
        if ((x % 5) == 0&&(x !=0))
        printf("/n");
        printf (" %-10. 10s" , data[x]) ;
    }
}
  
     在上例中,字符串數組char *data[]中包含了某年4個地區的銷售數據。顯然,你會要求按表格形式打印這些數據,而不是一個挨一個地毫無格式地打印這些數據。因此,上例中用下述語句來打印這些數據:
    printf("%-10.10s",data[x]);
    參數"%-10.10s"指示printf()函數按10個字符的長度打印一個字符串。在缺省情況下,printf()函數按右對齊格式打印字符串,但 是,在第一個10的前面加上減號(-)後,prinft()函數,就會使字符串左對齊。爲此,printf()函數會在字符串的尾部加入空格,以使其長度 達到10個字符。上例的打印輸出非常整潔,類似於一張表格,如下所示:

    REGION    --Q1--    --Q2--     --Q3--     --Q4--
    North    10090.50   12200.10   26653.12   62634.32
    SOuth    21662.37   95843.23   23788.23   48279.28
    East     23889.38   23789.05   89432.84   29874.48
    West     85933.82   74373.23   78457.23   28799.84

    請參見:   
    6.4怎樣使字符串右對齊?
  
    6.6.怎樣拷貝字符串的一部分?
    利用標準庫函數strncpy(),可以將一字符串的一部分拷貝到另一個字符串中。strncpy()函數有3個參數:第一個參數是目錄字符串;第二個參 數是源字符串;第三個參數是一個整數,代表要從源字符串拷貝到目標字符串中的字符數。以下是一個用strncpy()函數拷貝字符串的一部分的例子:  

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

void main(void);
void main (void)
{
    char * source_str = "THIS IS THE SOURCE STRING" ;
    char dest_strl[40]= {0}, dest_str2[40]= {0};
    / * Use strncpy() to copy only the first 11 characters. * /
    strncpy(dest_strl, source-str, 11);
    printf("How about that! dest-strl is now: '%s'!!!/n", dest-strl);
    / * Now, use strncpy() to copy only the last 13 characters. * /
    strncpy(dest_strl, source_str + (strlen(source_str)-l3) , 13);
    printf("Whoa! dest_str2 is now: '%s'!!!/n". dest_str2);
}

    在上例中,第一次調用strncpy()函數時,它將源字符串的頭11個字符拷貝到dest_str1中,這是一種相當直接的方法,你可能會經常用到。第 二次調用strncpy()函數時,它將源字符串的最後13個字符拷貝到dest_str2中,其實現過程爲:
    (1)用strlen()函數計算出source_str字符串的長度,即strlen(source_str)。
    (2)將source_str的長度減去13(13是將要拷貝的字符數),得出source_str中剩餘的字符數,即pstrlen(source_str)-13。
    (3)將strlen(source_str)-13和source_str的地址相加,得出指向source_str中倒數第13個字符的地址的指針, 即source_str+(strlen(source_str)-13)。這個指針就是strncpy()函數的第二個參數。
    (4)在strncpy()函數的第三個參數中指定要拷貝的字符是13。

上例的打印輸出如下所示:
    How about that! dest_str1 is now:'THIS IS THE'!!!
    Whoa! dest_str2 is now:'SOURCE STRING'!!!

    需要注意的是,在將source_str拷貝到dest_strl和dest_str2之前,dest_strl和dest_str2都要被初始化爲 null字符(/0)。這是因爲strncpy()函數在拷貝字符串時不會自動將null字符添加到目錄字符串後面,因此你必須確保在目標字符串的後面加 上null字符,否則會導致打印出一些雜亂無章的字符。

    請參見;
    6.1 串拷貝(strcpy)和內存拷貝(memcpy)有什麼不同?它們適合於在哪種情況下使用?
    6.9 怎樣打印字符串的一部分?

    6.7 怎樣將數字轉換爲字符串?
    C語言提供了幾個標準庫函數,可以將任意類型(整型、長整型、浮點型等)的數字轉換爲字符串。以下是用itoa()函數將整數轉換爲字符串的一個例子:

# include <stdio. h>
# include <stdlib. h>

void main (void);
void main (void)
{
    int num = 100;
    char str[25];
    itoa(num, str, 10);
    printf("The number 'num' is %d and the string 'str' is %s. /n" ,
                       num, str);
}
  
   itoa()函數有3個參數:第一個參數是要轉換的數字,第二個參數是要寫入轉換結果的目標字符串,第三個參數是轉移數字時所用的基數。在上例中,轉換基數爲10。

    下列函數可以將整數轉換爲字符串:
----------------------------------------------------------
    函數名                  作 用
----------------------------------------------------------
    itoa()                將整型值轉換爲字符串
    itoa()                將長整型值轉換爲字符串
    ultoa()               將無符號長整型值轉換爲字符串
----------------------------------------------------------
    請注意,上述函數與ANSI標準是不兼容的。能將整數轉換爲字符串而且與ANSI標準兼容的方法是使用sprintf()函數,請看下例:    
#include<stdio.h>  
# include <stdlib. h>

void main (void);
void main (void)
{
    int num = 100;
    char str[25];
    sprintf(str, " %d" , num);
   printf ("The number 'num' is %d and the string 'str' is %s. /n" ,
                          num, str);

}

   在將浮點型數字轉換爲字符串時,需要使用另外一組函數。以下是用fcvt()函數將浮點型值轉換爲字符串的一個例子:

# include <stdio. h>
# include <stdlib. h>

void main (void);
void main (void)
{
    double num = 12345.678;
    char * sir;
    int dec_pl, sign, ndigits = 3; /* Keep 3 digits of precision. * /
    str = fcvt(num, ndigits, &dec-pl, &sign); /* Convert the float
                                                 to a string. * /
    printf("Original number; %f/n" , num) ; /* Print the original
                                                 floating-point
                                                    value. * /
    printf ("Converted string; %s/n",str);    /* Print the converted
                                                string's value. * /
    printf ("Decimal place: %d/n" , dec-pi) ; /* Print the location of
                                                 the decimal point. * /
    printf ("Sign: %d/n" , sign) ;            /* Print the sign.
                                                 0 = positive,
                                                 1 = negative. * /
}

    fcvt()函數和itoa()函數有數大的差別。fcvt()函數有4個參數:第一個參數是要轉換的浮點型值;第二個參數是轉換結果中十進制小數點右側 的位數;第三個參數是指向一個整數的指針,該整數用來返回轉換結果中十進制小數點的位置;第四個參數也是指向一個整數的指針,該整數用來返回轉換結果的符 號(0對應於正值,1對應於負值)。
    需要注意的是,fcvt()函數的轉換結果中並不真正包含十進制小數點,爲此,fcvt()函數返回在轉換結果中十進制小數點應該佔據的位置。在上例中, 整型變量dec_pl的結果值爲5,因爲在轉換結果中十進制小數點應該位於第5位後面。如果你要求轉換結果中包含十進制小數點,你可以使用gcvt()函 數(見下表)。

    下列函數可以將浮點型值轉換爲字符串:
-------------------------------------------------------------------------
    函數名             作 用
-------------------------------------------------------------------------
    ecvt()    將雙精度浮點型值轉換爲字符串,轉換結果中不包含十進制小數點
    fcvt()    以指定位數爲轉換精度,餘同ecvt()
    gcvt()    將雙精度浮點型值轉換爲字符串,轉換結果中包含十進制小數點
-------------------------------------------------------------------------

    請參見:
    6.8 怎樣將字符串轉換爲數字?

    6.8 怎樣將字符串轉換爲數字?
    C語言提供了幾個標準庫函數,可以將字符串轉換爲任意類型(整型、長整型、浮點型等)的數字。以下是用atoi()函數將字符串轉換爲整數的一個例子:

# include <stdio. h>
# include <stdlib. h>

void main (void) ;
void main (void)
{
    int num;
    char * str = "100";
    num = atoi(str);
    printf("The string 'str' is %s and the number 'num' is %d. /n",
                   str, num);
}
  
   atoi()函數只有一個參數,即要轉換爲數字的字符串。atoi()函數的返回值就是轉換所得的整型值。   

    下列函數可以將字符串轉換爲數字:
------------------------------------------------------------------------
    函數名    作 用
------------------------------------------------------------------------
atof()     將字符串轉換爲雙精度浮點型值
atoi()     將字符串轉換爲整型值
atol()     將字符串轉換爲長整型值
strtod()   將字符串轉換爲雙精度浮點型值,並報告不能被轉換的所有剩餘數字
strtol()   將字符串轉換爲長整值,並報告不能被轉換的所有剩餘數字
strtoul() 將字符串轉換爲無符號長整型值,並報告不能被轉換的所有剩餘數字
------------------------------------------------------------------------  
  
將字符串轉換爲數字時可能會導致溢出,如果你使用的是strtoul()這樣的函數,你就能檢查這種溢出錯誤。請看下例:  
# include <stdio. h>
# include <stdlib. h>
# include <limits. h>

void main(void);
void main (void)
{
    char* str = "1234567891011121314151617181920" ;
    unsigned long num;
    char * leftover;
    num = strtoul(str, &leftover, 10);
    printf("Original string: %s/n",str);
    printf("Converted number: %1u/n" , num);
    printf("Leftover characters: %s/n" , leftover);
}

   在上例中,要轉換的字符串太長,超出了無符號長整型值的取值範圍,因此,strtoul()函數將返回ULONG_MAX(4294967295),並 使。char leftover指向字符串中導致溢出的那部分字符;同時,strtoul()函數還將全局變量errno賦值爲ERANGE,以通知函數的調用者發生了 溢出錯誤。函數strtod()和strtol()處理溢出錯誤的方式和函數strtoul()完全相同,你可以從編譯程序文檔中進一步瞭解這三個函數的 有關細節。

    請參見:
    6.7 怎樣將數字轉換爲字符串?

    6.9 怎樣打印字符串的一部分?   
    6.6 中討論了怎樣拷貝字符串的一部分,爲了打印字符串的一部分,你可以利用6.6的例子中的部分技巧,不過你現在要使用的是printf()函數,而不是sprintf()函數。請看下例:

# include <stdio. h>
# include <stdlib. h>

void main (void);
void main (void)
{
    char * source_str = "THIS IS THE SOURCE STRING" ;
    / * Use printfO to print the first 11 characters of source_str. * /
    printf("First 11 characters: ' %11. lls'/n" , source_str);
    / * Use printf() to print only the
        last 13 characters of source _str. * /
    printf("Last 13 characters:'%13.13'/n",
                    source_str+(strlen(source_str)-13));
}
    上例的打印輸出如下所示:   
    First 11 characters: 'THIS IS THE'   
    Last 13 characters:'SOURCE STRING'
    在上例中,第一次調用printf()函數時,通過指定參數"%11.11s",迫使printf()函數只打印11個字符的長度,因爲源字符串的長度大 於11個字符,所以在打印時源字符串將被截掉一部分,只有頭11個字符被打印出來。第二次調用printf()函數時,它將源字符串的最後13個字符打印 出來,其實現過程爲:
    (1)用strlen()函數計算出source_str字符串的長度,即strlen(source_str)。
    (2)將source_str的長度減去13(13是將要打印的字符數),得出source_str中剩餘字符數,且pstrlen(source_str)-13。
    (3)將strlen(source_str)-13和source_str的地址相加,得出指向source_str中倒數第13個字符的地址的指針; 即source_str+(strlen(source_str)-13)。這個指針就是printf()函數的第二個參數。
    (4)通過指定參數“%13.13s”,迫使printf()函數只打印13個字符的長度,其結果實際上就是打印源字符串的最後13個字符。

    請參見:
    6.1 串拷貝(strcpy)和內存拷貝(memcpy)有什麼不同?它們適合於在哪種情況下使用?
    6.6 怎樣拷貝字符串的一部分?

    6.10 怎樣判斷兩個字符串是否相同?
    C語言提供了幾個標準庫函數,可以比較兩個字符串是否相同。以下是用strcmp()函數比較字符串的一個例子:
  
#include <stdio. h>
#include <string. h>

void main (void);
void main(void)
{
    char* str_1 = "abc" ; char * str_2 = "abc" ; char* str_3 = "ABC" ;
    if (strcmp(str_1, str_2) == 0)
        printf("str_1 is equal to str_2. /n");
    else
        printf("str_1 is not equal to str_2. /n");
    if (strcmp(str_1, str_3) == 0)
       printf("str_1 is equal to str_3./n");
    else
        printf("str_1 is not equalto str_3./n");
}
    
    上例的打印輸出如下所示:   
    str_1 is equal to str_2.   
    str_1 is not equal to str_3.
   
    strcmp()函數有兩個參數,即要比較的兩個字符串。strcmp()函數對兩個字符串進行大小
寫敏感的(case-sensitiVe)和字典式的(lexicographic)比較,並返回下列值之一:
----------------------------------------------------
    返 回 值         意 義
----------------------------------------------------
    <0               第一個字符串小於第二個字符串
     0               兩個字符串相等    ·
    >0               第一個字符串大於第二個字符串
----------------------------------------------------
    在上例中,當比較str_1(即“abc”)和str_2(即“abc”)時,strcmp()函數的返回值爲0。然
而,當比較str_1(即"abc")和str_3(即"ABC")時,strcmp()函數返回一個大於0的值,因爲按
ASCII順序字符串“ABC”小於“abc”。
    strcmp()函數有許多變體,它們的基本功能是相同的,都是比較兩個字符串,但其它地方
稍有差別。下表列出了C語言提供的與strcmp()函數類似的一些函數:   
-----------------------------------------------------------------
    函 數 名                   作 用
-----------------------------------------------------------------
    strcmp()         對兩個字符串進行大小寫敏感的比較
    strcmpi()        對兩個字符串進行大小寫不敏感的比較
    stricmp()        同strcmpi()
    strncmp()        對兩個字符串的一部分進行大小寫敏感的比較
    strnicmp()       對兩個字符串的一部分進行大小寫不敏感的比較
-----------------------------------------------------------------
    在前面的例子中,如果用strcmpi()函數代替strcmp()函數,則程序將認爲字符串“ABC”
等於“abc”。

    請參見:
    6.1 串拷貝(strcpy)和內存拷貝(memcpy)有什麼不同?它們適合於在哪種情況下使用?

 

原地址 http://hi.baidu.com/tq0330/blog/item/2488c4a2ff24efa9caefd071.html

 

======================================================================

1. c++中string到int的轉換

1) 在C標準庫裏面,使用atoi:

#include <cstdlib>
#include <string>

std::string text = "152";
int number = std::atoi( text.c_str() );
if (errno == ERANGE) //可能是std::errno
{
//number可能由於過大或過小而不能完全存儲
}
else if (errno == ????)
//可能是EINVAL
{
//不能轉換成一個數字
}

2) 在C++標準庫裏面,使用stringstream:(stringstream 可以用於各種數據類型之間的轉換)

#include <sstream>
#include <string>

std::string text = "152";
int number;
std::stringstream ss;


ss << text;//可以是其他數據類型
ss >> number; //string -> int
if (! ss.good())
{
//錯誤發生
}

ss << number;// int->string
string str = ss.str();
if (! ss.good())
{
//錯誤發生
}

3) 在Boost庫裏面,使用lexical_cast:

#include <boost/lexical_cast.hpp>
#include <string>

try
{
std::string text = "152";
int number = boost::lexical_cast< int >( text );
}
catch( const boost::bad_lexical_cast & )
{
//轉換失敗
}                      

2.string 轉 CString
CString.format(”%s”, string.c_str());
用c_str()確實比data()要好;

3.char 轉 CString
CString.format(”%s”, char*);

4.char 轉 string
string s(char *);
只能初始化,在不是初始化的地方最好還是用assign().

5.string 轉 char *
char *p = string.c_str();

6.CString 轉 string
string s(CString.GetBuffer());
GetBuffer()後一定要ReleaseBuffer(),否則就沒有釋放緩衝區所佔的空間.

7.字符串的內容轉換爲字符數組和C—string
(1) data(),返回沒有”/0“的字符串數組
(2) c_str(),返回有”/0“的字符串數組
(3) copy()

8.CString與int、char*、char[100]之間的轉換

(1) CString互轉int

將字符轉換爲整數,可以使用atoi、_atoi64或atol。而將數字轉換爲CString變量,可以使用CString的Format函數。如
CString s;
int i = 64;
s.Format(”%d”, i)
Format函數的功能很強,值得你研究一下。

void CStrDlg::OnButton1()
{
    CString
    ss=”1212.12″;
    int temp=atoi(ss);
    CString aa;
    aa.Format(”%d”,temp);
    AfxMessageBox(”var is ” + aa);
}

(2) CString互轉char*

///char * TO cstring
CString strtest;
char * charpoint;
charpoint=”give string a value”; //?
strtest=charpoint;

///cstring TO char *
charpoint=strtest.GetBuffer(strtest.GetLength());

(3) 標準C裏沒有string,char *==char []==string, 可以用CString.Format(”%s”,char *)這個方法來將char *轉成CString。
     要把CString轉成char *,用操作符(LPCSTR)CString就可以了。
     CString轉換 char[100]
    char a[100];
    CString str(”aaaaaa”);
    strncpy(a,(LPCTSTR)str,sizeof(a));

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