我正在写一个代码打印一个字符串的首字母。但我有一个问题,在一个例子中,这些名字有不止一个空格characters.And,我想出了一个想法,删除那些不需要的空格字符,只留下一个空格,但我对字符串还没有信心,谁能告诉我该怎么做吗?
#include <iostream>
#include <string>
#include <cctype>
std::string initials(const std::string &w )
{
char space = ' ';
std::string a;
a.push_back(w[0]);
for (int i = 0; i < w.size(); ++i)
{
if (w[i] == space )
{
a.push_back(w[i+1]);
}
}
return a;
}
int main()
{
std::cout<< initials(std::string("Julian Rodriguez Antonio "))<<std::endl;
}发布于 2020-05-06 15:15:46
如果最后一个字符是空格或非空格,则可以将这些信息保存在内存中。
#include <iostream>
#include <string>
#include <cctype>
std::string initials(const std::string &w) {
char space = ' ';
std::string a;
int mode = 0;
for (int i = 0; i < w.size(); ++i) {
if (w[i] == space) {
mode = 0;
} else {
if (mode == 0) a.push_back(w[i]);
mode = 1;
}
}
return a;
}
int main()
{
std::cout<< initials(std::string(" Julian Rodriguez Antonio "))<<std::endl;
}编辑:感谢Pete的建议,这里有一个更清晰的实现。
std::string initials(const std::string &w) {
char space = ' ';
std::string a;
bool skipping_spaces = true;
for (int i = 0; i < w.size(); ++i) {
if (w[i] == space) {
skipping_spaces = true;
} else {
if (skipping_spaces) a.push_back(w[i]);
skipping_spaces = false;
}
}
return a;
}https://stackoverflow.com/questions/61638512
复制相似问题