在 for 循环中更新两个变量时遇到问题C++

Trouble getting two variables to update in C++ for loop

本文关键字:变量 两个 遇到 C++ 问题 循环 for 更新      更新时间:2023-10-16

我正在创建一个将句子拆分为单词的函数,并相信这样做的方法是使用str.substr,从str[0]开始,然后使用 str.find 查找第一个" "字符的索引。 然后更新 str.find 的起始位置参数,从该" "字符的索引开始,直到str.length()结束。

我使用两个变量来标记单词的起始位置和结束位置,并用最后一个的结束位置更新起始位置变量。但是它没有像我目前那样在循环中按预期更新,并且无法弄清楚原因。

#include <iostream>
#include <string>
using namespace std;
void splitInWords(string str);

int main() {
string testString("This is a test string");
splitInWords(testString);
return 0;
}

void splitInWords(string str) {
int i;
int beginWord, endWord, tempWord;
string wordDelim = " ";
string testWord;
beginWord = 0;
for (i = 0; i < str.length(); i += 1) {
endWord = str.find(wordDelim, beginWord);
testWord = str.substr(beginWord, endWord);
beginWord = endWord;
cout << testWord << " ";
}
}

使用字符串流更容易。

#include <vector>
#include <string>
#include <sstream>
using namespace std;
vector<string> split(const string& s, char delimiter)
{
vector<string> tokens;
string token;
istringstream tokenStream(s);
while (getline(tokenStream, token, delimiter))
{
tokens.push_back(token);
}
return tokens;
}
int main() {
string testString("This is a test string");
vector<string> result=split(testString,' ');
return 0;
}

您可以使用现有的C++库编写它:

#include <string>
#include <vector>
#include <iterator>
#include <sstream>
int main()
{
std::string testString("This is a test string");
std::istringstream wordStream(testString);
std::vector<std::string> result(std::istream_iterator<std::string>{wordStream},
std::istream_iterator<std::string>{});
}

几个问题:

  1. substr()方法第二个参数是长度(不是位置(。

    // Here you are using `endWord` which is a poisition in the string.
    // This only works when beginWord is 0
    // for all other values you are providing an incorrect len.
    testWord = str.substr(beginWord, endWord); 
    
  2. find()方法从第二个参数中搜索。

    // If str[beginWord] contains one of the delimiter characters
    // Then it will return beginWord
    // i.e. you are not moving forward.
    endWord = str.find(wordDelim, beginWord);
    // So you end up stuck on the first space.
    
  3. 假设您修复了上述问题。您将在每个单词的前面添加空格。

    // You need to actively search and remove the spaces
    // before reading the words.
    

你可以做的好事:

这里:

void splitInWords(string str) {

您正在按值传递参数。这意味着您正在制作副本。更好的技术是通过 const 引用传递(您没有修改原始或副本(。

void splitInWords(string const& str) {

另一种选择

您可以使用流功能。

void split(std::istream& stream)
{
std::string word;
stream >> word;     // This drops leading space.
// Then reads characters into `word`
// until a "white space" character is
// found.
// Note: it emptys words before adding any
}