C++ - 为字符串添加空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20391415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ - Adding Spaces to String
提问by ScottOBot
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 whatsand then stops. What is going on I can't seem to make this very simple code work.
出于某种原因,输出只给出hey whats然后停止。这是怎么回事我似乎无法让这个非常简单的代码工作。
采纳答案by Abhishek Bansal
After reading "hey"and "whats", the value of iis more than the length of "hello"and hence no such substring exists for the code input.substr(lastFind, i).
读取"hey"and 后"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] + " ";
}
回答by Jules G.M.
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;
}

