在C++中拆分字符串的3种方法

561 阅读1分钟

在这篇文章中,我们将看到在C++中分割字符串的不同方法。这涉及到find()、substr()等的使用。

将一个字符串分割成若干个单词,这叫做分割字符串。没有预定义的函数可以将一个字符串分割成若干个子串,所以我们将讨论一些可以进行分割的方法。

C++中拆分字符串的一些方法

1.使用find()和substr()函数

使用这种方法,我们可以将包含分隔符的字符串分割成若干个子字符串。

分隔符是一个独特的字符或一系列字符,表示特定语句或字符串的开始或结束。这些定界符不需要仅仅是一个空位,可以是任何字符或一组字符。

C++程序

#include <bits/stdc++.h>
using namespace std;
 
void splitstr(string str, string deli = " ")
{
    int start = 0;
    int end = str.find(deli);
    while (end != -1) {
        cout << str.substr(start, end - start) << endl;
        start = end + deli.size();
        end = str.find(deli, start);
    }
    cout << str.substr(start, end - start);
}
int main()
{
    string s = "This&&is&&an&&Article&&at&&OpenGenus"; // Take any string with any delimiter 
    splitstr(s, "&&");
    cout << endl;
 
    return 0;
}

输出

This 
is
an 
Article
at
OpenGenus

在这个程序中,我们在while循环中使用**find()函数来重复查找定界符的出现,每次找到定界符后,我们使用substr()**函数来打印子串,然后我们将start变量指向最后打印的子串的末尾,然后再次找到定界符并打印子串。这个过程一直持续到我们找到所有的子串为止。

2.使用自定义的splitStr()函数

C++程序

#include <bits/stdc++.h>  
using namespace std;  
void SplitStr(string str)
{
    string s = "";
    cout<<"The split string is:"
    for (auto x : str)
    {
        if (x == ' ')
        {
            cout << s << endl;
            s = "";
        }
        else {
            s = s + x;
        }
    }
    cout << s << endl;
}
 
int main()
{
    string str = "Opengenus Article to Split the String";
    SplitStr(str);
    return 0;
}

以上是使用我们的自定义splitstr()函数来分割字符串的代码

该代码的具体执行步骤如下

  1. 初始化字符串str,并调用**splitSrt()**函数,将str作为参数传入。
  2. 将s作为一个临时字符串,我们将在s中存储字符串,直到我们得到一个分隔符(本例中是空格)。
  3. 当遇到定界符时,字符串s被打印出来并重新初始化为空字符串。
  4. 这个过程重复进行,直到字符串全部结束。

输出

The split string is:
 Opengenus
 Article 
 to 
 Split
 the 
 String

3.使用strtok()函数

strtok()是一个函数,它在第一次调用时给出字符串中第一个标记的指针,在第二次调用时给出第二个标记的指针,直到字符串中不再有标记。
在返回字符串中最后一个标记的指针后,它返回NULL指针。

如何使用

char *ptr = strtok( str, delim)

其中str是字符串,deleim是分隔符或我们想在字符串中搜索的标记。它可以是任何东西,例如:逗号(,),空格( ),连字符(-)等。

C++程序

#include <iostream>  
#include <cstring>  
using namespace std;  
  
int main()  
{  
    char str[100]; // declare the size of string      
    cout << " Enter a string: " <<endl;  
    cin.getline(str, 100); // use getline() function to read a string from input stream  
      
    char *ptr; // declare a ptr pointer  
    ptr = strtok(str, " , "); // use strtok() function to separate string using comma (,) delimiter.  
    cout << " Split string using strtok() function: " << endl;   
    while (ptr != NULL)  
    {  
        cout << ptr  << endl; // print the string token  
        ptr = strtok (NULL, " , ");  
    }  
    return 0;
 }

输出

Enter a string: 
This is one of the way to split a string in C++

Split string using strtok() function:
This 
is 
one 
of
the
way
to
split
a
string
in
C++

通过OpenGenus的这篇文章,你一定对如何在C++中分割字符串有了一个完整的概念。