歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux綜合 >> Linux資訊 >> 更多Linux >> C++常用字符串處理函數及使用示例

C++常用字符串處理函數及使用示例

日期:2017/2/27 9:27:10   编辑:更多Linux
  char *strcpy(char *s1, const char *s2)    將字符串s2復制到字符串數組s1中,返回s1的值    char *strncpy(char *s1, const char *s2, size_t n)    將字符串s2中最多n個字符復制到字符串數組s1中,返回s1的值    char *strcat(char *s1, const char *s2)    將字符串s2添加到字符串s1的後面。s2的第一個字符重定義s1的null終止符。返回s1的值    char *strncat(char *s1, const char *s2, size_t n)    將字符串s2中最多n個字符添加到字符串s1的後面。s2的第一個字符重定義s1的null終止符。返回s1的值    int strcmp(const char *s1, const char *s2)    比較字符串s1和字符串s2。函數在s1等於、小於或大於s2時分別返回0、小於0或者大於0的值    int strncmp(const char *s1, const char *s2, size_t n)    比較字符串s1中的n個字符和字符串s2。函數在s1等於、小於或大於s2時分別返回0、小於0或者大於0的值    char * strtok(char *s1,const char *s2)    用一系列strtok調用將s1字符串標記化(將字符串分成各個邏輯組件,如同一行文本中的每個單詞),用字符串s2所包含的字符分隔。 首次調用時包含s1為第一個參數,後面調用時繼續標記化同一字符串,包含NULL為第一個參數。每次調用時返回當前標記指針。如果函數調用時不再有更多標記,則返回NULL    ize_t strlen(const char *s)    確定字符串長度,返回null終止符之前的字符數    使用示例:    //源代碼在Visual c++6.0環境下編譯通過    #include <iostream.h>    #include <string.h>    int main()    {    char str1[50] = "Happy birthday to ", str2[] = "coffeehu";    char temp1[100],temp2[6], * temp;    char str[] = "This is a sentence with 7 tokens";    trcpy(temp1, str1);    trncpy(temp2, str1, 5);    temp2[5] = '\0';    cout << "strcpy result: " <<temp1 << "\n";    cout << "strncpy result: " << temp2 << "\n";    cout << "strcat result: " << strcat(str1, str2) << "\n";    cout << "strncat result: " << strncat(str1, str2, 6) <<"\n";    cout << "strcmp result: " << strcmp(temp2,"Happ") <<"\n";    cout << "strncmp result: " << strncmp(str1,"Happy",5) <<"\n";    //strtok function eg.    temp = strtok(str, " ");    while(temp != NULL)    {    cout << temp <<'\n';    temp = strtok(NULL, " ");    }    cout << "strlen result: " << strlen(str2) <<"\n";    return 0;    }




Copyright © Linux教程網 All Rights Reserved