[英]C++ function to split strings
我最近開始使用 Accelerated C++ 一書開始學習 C++。 本書介紹了以下 function 將字符串拆分為基於空格字符的子字符串
vector<string> split(const string& s)
{
vector<string> ret;
typedef string::size_type string_size;
string_size i = 0;
while (i != s.size()) {
// ignore leading blanks
// invariant: characters in range[original i, current i) are all spaces
while (i != s.size() && isspace(s[i]))
++i;
// find the end of next word
string_size j = i;
// invariant: none of the characters in range [original j, current j) is a space
while (j != s.size() && !isspace(s[j]))
j++;
if (i != j) {
// copy from s starting at i and taking j-i chars
ret.push_back(s.substr(i, j - i));
i = j;
}
}
return ret;
}
我的目標是使用這個 function 根據逗號分割字符串。 所以我將!isspace(s[j])
部分更改為s[j],= ','
以便 function 使用逗號來識別單詞的結尾。 我嘗試測試 function 如下:
int main() {
string test_string = "this is ,a test ";
vector<string> test = split(test_string);
for (vector<string>::const_iterator it = test.begin(); it != test.end(); ++it)
cout << *it << endl;
return 0;
}
當我在終端中編譯 function 時,如下所示
g++ -o test_split_function test_split_function.cpp
我沒有錯誤。 但是,當我運行腳本時,它會繼續運行並且不會在我的命令行中生成任何 output。 我不明白為什么,因為基於空格將字符串拆分為單詞的 function 確實在同一個字符串上運行。
問題:我做錯了什么? s[j],= ','
語句不正確嗎?
有兩個部分需要替換isspace()
function,一個用於i
循環:
while (i != s.size() && s[i]==',')
++i;
一個用於j
循環:
while (j != s.size() && s[j]!=',')
j++;
這將起作用。
我對此代碼進行了一些更改。 將 ispace function 替換為s[j]==','
或s[j],=','
檢查出來。
#include<bits/stdc++.h>
using namespace std;
vector<string> split(const string& s)
{
vector<string> ret;
typedef string::size_type string_size;
string_size i = 0;
while (i != s.size()) {
// ignore leading blanks
// invariant: characters in range[original i, current i) are all spaces
while (i != s.size() && s[i]==',')
++i;
// find the end of next word
string_size j = i;
// here i changed isspace with s[j]!=','
while (j != s.size() && s[j]!=',')
j++;
if (i != j) {
// copy from s starting at i and taking j-i chars
ret.push_back(s.substr(i, j - i));
i = j;
}
}
return ret;
}
int main()
{
string test_string = "this is ,a test ";
vector<string> test = split(test_string);
for (vector<string>::const_iterator it = test.begin(); it != test.end(); ++it)
cout << *it << endl;
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.