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

版权声明:本人小白,有错误之处恳请指出,感激不尽;欢迎转载 https://blog.csdn.net/stone_fall/article/details/88640469

目录

函数介绍

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

猜你喜欢

转载自blog.csdn.net/stone_fall/article/details/88640469