我的分裂句功能有问题 我的函数的想法拆分任何句子并将其添加到数组,如
示例:
句子:: Hello world。
我的函数将起作用::(array [0] = hello,array [1] = world)。
这是我的代码
void splitSentence(char *Sentence, char symb){
const int Size = strlen(Sentence);
string SentenceResult[2];
int count= 0;
stringstream stream;
for(int i=0;i<Size;i++){
stream << Sentence[i];
if((Sentence[i] == symb) || (Sentence[i] == '\0')){
SentenceResult[count] = stream.str();
count++;
stream.str(" ");
}
}
cout << "Stream: " << stream.str() << endl;
cout << "Word [0]: " << SentenceResult[0] << endl;
cout << "Word [1]: " << SentenceResult[1] << endl;
}
结果
流:世界
array [0]:你好 array [1]:// empty(必须是“world”)
我的功能有什么问题。
为什么数组[1]为空。
答案 0 :(得分:1)
您的for
循环运行得不够,无法进入Sentence[i] == '\0'
案例。它只会运行到“hello world”的“d”,因此流的conent不会再写入输出数组。
你可以写一下:
const int Size = strlen(Sentence)+1;
你已经包含了最后的空字节。
答案 1 :(得分:1)
const int Size = strlen(Sentence);
这会计算字符串数据的长度,但不最终的空终止符,因此您的循环将找不到终结符,并且不会包含最后一个单词。您希望在此值中添加一个以获取已终止字符串的完整长度。
答案 2 :(得分:1)
您只需要更改for
循环:
for(int i=0; i <= Size; i++)