在C ++中标记字符串

在本节中,我们将看到如何在C ++中标记字符串。在C语言中,我们可以将strtok()函数用于字符数组。这里我们有一个字符串类。现在,我们将看到如何使用字符串中的一些定界符来剪切字符串。

要使用C ++功能,我们必须将字符串转换为字符串流。然后使用getline()函数我们可以完成任务。该getline()函数接收字符串流,另一个字符串发送输出,并使用定界符停止流的扫描。

让我们看下面的例子,以了解该函数是如何工作的。

范例程式码

#include <iostream>
#include <vector>
#include <sstream>
using namespace std;

int main() {
   string my_string = "Hello,World,India,Earth,London";
   stringstream ss(my_string); //convert my_string into string stream

   vector<string> tokens;
   string temp_str;

   while(getline(ss, temp_str, ',')){ //use comma as delim for cutting string
      tokens.push_back(temp_str);
   }
   for(int i = 0; i < tokens.size(); i++) {
      cout << tokens[i] << endl;
   }
}

输出结果

Hello
World
India
Earth
London