C ++-在字符串中添加空格 [英] C++ - Adding Spaces to String

查看:1029
本文介绍了C ++-在字符串中添加空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

#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,然后停止.发生什么了,我似乎无法使这个非常简单的代码起作用.

For some reason the output only gives hey whats and then stops. What is going on I can't seem to make this very simple code work.

推荐答案

在读取"hey""whats"之后,i的值大于"hello"的长度,因此对于代码input.substr(lastFind, i).

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).

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

You should check for the length of possible substring (dictionary[j]) and not 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] + " ";
            }

这篇关于C ++-在字符串中添加空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆