我想将一个带空格的单个字符串拆分为三个单独的字符串。例如,我有一个字符串(str1)。用户输入任何3个单词,如 "Hey it's me"
或"It's hot out"
。 从那里,我需要写一个函数,将采取此字符串(str1)并将其分成三个不同的字符串。这样(以第一个例子),那么它会说:在空格处拆分一个句子(字符串)
Hey (is the first part of the string)
it's (is the second part of the string)
me (is the third part of the string)
我有我应该使用拆分在空间中的字符串,操作难度。
这是我的代码到目前为止,这仅仅是用户将如何进入input.I正在寻找做到这一点使用istringstream
没有最基本的方法!只使用基本的字符串操作,如find(),substr()。
**我期待创建一个单独的功能执行字符串的分手**我想出如何使用此代码获取输入的第一部分:
cout << "Enter a string" << endl;
getline(cin, one);
position = str1.find(' ', position);
first_section = str1.substr(0, position);
但现在我不知道如何将字符串的第二部分或第三部分分成自己的字符串。我正在考虑一个for循环可能?不确定。
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1;
cout << "Enter three words: ";
getline(cin, str1);
while(cin) {
cout << "Original string: " << str1 << endl;
cin >> str1;
}
return;
}
你可以考虑使用C函数去做?例如。 'strtok'? – Elyasin
我只严格使用C++ – Alyssa
关于如何在C++中分割字符串有很多帖子,最简单的一个不需要你编写专门的函数来完成它。那样就是使用'std :: istringstream'。 – PaulMcKenzie