C ++ - 向String添加空格

时间:2013-12-05 04:24:42

标签: c++ string parsing substr

嘿所以我正在尝试编写一个简单的程序,为C ++中没有的给定字符串添加空格,这里是我编写的代码:

#include <iostream>
#include <string>

using namespace std;

string AddSpaceToString (string input)
{
    const int arrLength = 5;
    int lastFind = 0;
    string output;
    string dictionary[arrLength] = {"hello", "hey", "whats", "up", "man"};

    for (int i = 0; i < input.length(); i++)
    {
        for (int j = 0; j < arrLength; j++)
        {
            if(dictionary[j] == input.substr(lastFind, i))
            {
                lastFind = i;
                output += dictionary[j] + " ";
            }
        }
    }

    return output;
}

int main ()
{
    cout << AddSpaceToString("heywhatshelloman") << endl;

    return 0;
} 

由于某种原因,输出仅提供hey whats然后停止。发生了什么我似乎无法使这个非常简单的代码工作。

2 个答案:

答案 0 :(得分:3)

在阅读"hey""whats"后,i的值超过"hello"的长度,因此代码input.substr(lastFind, i)不存在此类子字符串

您应该检查可能的子字符串(dictionary[j])而不是i的长度。

input.substr( lastFind, dictionary[j].size() )

此外,您还需要更改:

lastFind += dictionary[j].size();

所以if循环变为:

if(dictionary[j] == input.substr(lastFind, dictionary[j].size() ))
            {
                lastFind += dictionary[j].size();
                output += dictionary[j] + " ";
            }

答案 1 :(得分:1)

这是有效的

#include <iostream>
#include <string>

using namespace std;

string AddSpaceToString (string input)
{
    const int arrLength = 5;
    unsigned int lastFind = 0;
    string output;
    string dictionary[arrLength] = {"hello", "hey", "whats", "up", "man"};

    for (int j = 0; lastFind < input.size() && j < arrLength; ++j)
    {       

         if(dictionary[j] == input.substr(lastFind, dictionary[j].size()))
         {
            lastFind += dictionary[j].size();
            output += dictionary[j] + " ";
            j = -1;
         }
    }

    return output;
}

int main ()
{
    cout << AddSpaceToString("heywhatshelloman") << endl;

    return 0;
}