C/C++ | 字符串數組的分割和string的分割 | strtok()函數 | find()和substr()函數

目錄

函數介紹

strtok

char*類型分割

輸出

查找(find)

substr

string類型分割

輸出結果:


函數介紹

strtok

語法:

#include <string.h>
char *strtok( char *str1, const char *str2 );

功能:函數返回字符串str1中緊接“標記”的部分的指針, 字符串str2是作爲標記的分隔符。如果分隔標記沒有找到,函數返回NULL。爲了將字符串轉換成標記,第一次調用str1 指向作爲標記的分隔符。之後所以的調用str1 都應爲NULL。

例如:

char str[] = "now # is the time for all # good men to come to the # aid of their country";
char delims[] = "#";
char *result = NULL;
result = strtok( str, delims );
while( result != NULL ) {
    printf( "result is \"%s\"\n", result );
    result = strtok( NULL, delims );
}

以上代碼的運行結果是:

    result is "now "
    result is " is the time for all "
    result is " good men to come to the "
    result is " aid of their country"

char*類型分割

int main(){
    char buf[100]="192.168.1.1";
    char delims[] = ".";
    char *result = NULL;
    result = strtok( buf, delims );
    while(result!=NULL){
        printf( "%s\n", result );
        result = strtok( NULL, delims );
    }
    return 0;
}

輸出

192
168
1
1

查找(find)

語法:

  size_type find( const basic_string &str, size_type index );
  size_type find( const char *str, size_type index );
  size_type find( const char *str, size_type index, size_type length );
  size_type find( char ch, size_type index );

find()函數:

  • 返回str在字符串中第一次出現的位置(從index開始查找)如果沒找到則返回string::npos,
  • 返回str在字符串中第一次出現的位置(從index開始查找,長度爲length)。如果沒找到就返回string::npos,
  • 返回字符ch在字符串中第一次出現的位置(從index開始查找)。如果沒找到就返回string::npos

例如,

    string str1( "Alpha Beta Gamma Delta" );
    unsigned int loc = str1.find( "Omega", 0 );
    if( loc != string::npos )
      cout << "Found Omega at " << loc << endl;
    else
      cout << "Didn't find Omega" << endl;

substr

語法:

  basic_string substr( size_type index, size_type num = npos );

substr()返回本字符串的一個子串,從index開始,長num個字符。如果沒有指定,將是默認值 string::npos。這樣,substr()函數將簡單的返回從index開始的剩餘的字符串。

例如:

string s("What we have here is a failure to communicate"); 
string sub = s.substr(21); 
cout << "The original string is " << s << endl; 
cout << "The substring is " << sub << endl;

顯示:

The original string is What we have here is a failure to communicate 
The substring is a failure to communicate

string類型分割

int main()
{
    string str="192.168.1.1";
    int pos1=0,pos2=0;
    string pattern = ".";
    str +=pattern;
    string s[4];
    for(int i=0;i<4;i++){
        pos2=str.find(pattern,pos1);
        //cout<<pos1<<" "<<pos2<<endl;
        s[i] = str.substr(pos1,pos2-pos1);
        pos1=pos2+1;
    }
    for(int i=0;i<4;i++){
        cout<<s[i]<<endl;
    }
    return 0;
}

輸出結果:

192
168
1
1

 

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