我已經成功地寫出下面的代碼:拆分句子和檢索特定單詞
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string sentence;
getline(cin, sentence);
char* ptr = &sentence[0];
while (*ptr != '\0'){
if (*ptr == ' '){
cout << endl;
}
else{
cout << *ptr;
}
ptr++;
}
}
使用,我可以單獨打印一個句子的每個單詞。不過,我想存儲它們,然後檢索它們。下面是一個示例運行:
Enter the sentence:This is a sample sentence.
Which word do you want to see ?:4
sample
我不知道如何從上面的代碼繼續。我認爲將每個字母存儲在char數組中,然後將這些數組轉換爲字符串並將它們存儲在vector<string>
中,但無法弄清楚。
我想這樣做只使用給定的庫,如果可能的話,不使用任何分割函數。
編輯:這是我最近試過的。雖然沒有工作。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
char letter;
vector<string> words;
vector<char> temp;
vector<char> sentence;
while(cin >> letter){ // ctrl-z to break
sentence.push_back(letter);
}
char* ptr = &sentence[0];
while (*ptr != '\0'){
while (*ptr != ' '){
temp.push_back(*ptr);
ptr++;
}
words.push_back(str(temp));
}
}
EDIT2:這裏是用sstream
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
cout << "Sentence: " << endl;
string sentence;
getline(cin, sentence);
istringstream sin(sentence);
vector<string> tokens;
string word;
while (!sin.eof()){
sin >> word;
tokens.push_back(word);
}
cout << "Which word ?: " << endl;
int n;
cin >> n;
cout << tokens[n - 1] << endl;
}
EDIT3的解決方案:儀式,得到了it.Here就是我想要的解決方案。
#include <iostream>
#include <string>
using namespace std;
int wordbyword(string sentence, char** words)
{
int i = 0, j = 0, k = 0;
while (sentence[i] != '\0'){
if (sentence[i] != ' '){
words[j][k] = sentence[i];
k++;
}
else {
j++;
k = 0;
}
i++;
}
return j;
}
int main()
{
string sentence;
cout << "Sentence: "<< endl;
getline(cin, sentence);
int size = sentence.length();
char** words = new char*[size];
for (int i = 0; i < size; i++)
words[i] = new char[size];
int wordCount = wordbyword(sentence, words) + 1;
while(1){
cout << "Word number: " << endl;
int n;
cin >> n;
if (n == 0){
cout << "Terminating..." << endl;
break;
}
else if (n > wordCount || n < 0)
cout << "Word doesn't exist" << endl;
else
cout << words[n - 1] << endl;
}
}
你可以指望的空格,您到目前爲止看到的數字。第四個詞在第三個空格之後。 (根據你對單詞的定義,事情會變得更復雜) – Josay
你可以使用'std :: istringstream',然後用'>>'讀入'std :: string'。這將分割空白。 – BoBTFish
'std :: stringstream'就是爲此而做的。 ('#包括')。 –