简体   繁体   English

C ++-在字符串中添加空格

[英]C++ - Adding Spaces to String

Hey so I am trying to write a simple program that adds spaces to a given string that has none in C++ here is the code I have written: 嘿,所以我试图编写一个简单的程序,将空格添加到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;
} 

For some reason the output only gives hey whats and then stops. 出于某种原因,只输出给hey whats ,然后停止。 What is going on I can't seem to make this very simple code work. 发生的事情我似乎无法使这个非常简单的代码起作用。

After reading "hey" and "whats" , the value of i is more than the length of "hello" and hence no such substring exists for the code input.substr(lastFind, i) . 在读取"hey""whats"i的值大于"hello"的长度,因此对于代码input.substr(lastFind, i)不存在此类子字符串。

You should check for the length of possible substring ( dictionary[j] ) and not i . 您应该检查可能的子字符串( dictionary[j] )的长度,而不是i

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

Also you will have to change: 另外,您将必须更改:

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

So the if loop becomes: 因此,if循环变为:

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

this works 这有效

#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;
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM