如何在不使用任何库函数的情况下以简单方式从字符串中删除标点符号和空格?C++从字符串中删除标点符号和空格
回答
int main()
{
string s = "abc de.fghi..jkl,m no";
for (int i = 0; i < s.size(); i++)
{
if (s[i] == ' ' || s[i] == '.' || s[i] == ',')
{
s.erase(i, 1); // remove ith char from string
i--; // reduce i with one so you don't miss any char
}
}
cout << s << endl;
}
'std :: string :: operator []'是一个库函数,所以这段代码不符合不使用任何库函数的要求。
假设你可以使用图书馆的I/O像<iostream>
和类型,如std::string
,你只是不希望使用<cctype>
功能,如ispunct()
。
#include <iostream>
#include <string>
int main()
{
const std::string myString = "This. is a string with ,.] stuff in, it.";
const std::string puncts = " [];',./{}:\"?><`~!-_";
std::string output;
for (const auto& ch : myString)
{
bool found = false;
for (const auto& p : puncts)
{
if (ch == p)
{
found = true;
break;
}
}
if (!found)
output += ch;
}
std::cout << output << '\n';
return 0;
}
没有关于性能的信息,我敢肯定它可以以多种更好的方式完成。
恩,(明显是人为的)约束是不使用任何**库函数。 'std :: string'的构造函数是一个库函数。
那么还不如去C风格并使用数组,甚至不得不使用'strlen()','strcat()'或者甚至是'printf()'等函数。我怀疑他的要求是严格的,但由于他没有详细猜测我们永远不会知道。 – sharyex
我怀疑的重点是编写自己的'strlen'和'strcat'的等价物;他们并不那么难。 'printf',另一方面,... –
- 1. 从字符串中删除标点符号和空格
- 2. 从c中的字符串中删除标点符号和空格?
- 3. 从字符串中删除所有空格和标点符号(不是字母)?
- 4. C++从字符串中删除标点符号
- 5. 如何从字符串中删除标点符号C
- 6. 如何从字符串中删除所有符号和空格?
- 7. C++分割字符串,空格和标点符号
- 8. 从字符串C#删除点字符
- 9. 从长字符串空格中删除单个空格字符
- 10. 从字符串中删除字母字符和空格
- 11. 从VB.net中的字符串中删除所有标点符号
- 12. 如何从Python中的字符串中删除标点符号?
- 13. 从字符串中删除撇号和空格
- 14. JavaScript从字符串中删除全屏,逗号和空格
- 15. 只从字符串中删除空格
- 16. awk从字符串中删除空格
- 17. QStringList从字符串中删除空格
- 18. 从字符串中删除空格
- 19. 从字符串中删除空格
- 20. 从字符串中删除空格
- 21. 如何从字符串中删除标点符号? (Python)
- 22. 如何从字符串中删除双字符和空格
- 23. 从字符串中删除空格和特殊字符
- 24. 删除空格和标点符号从列表
- 25. 从字符串中删除空行C++
- 26. 从unicode字符串去除特殊字符和标点符号
- 27. 从字符串中删除字符串模式和符号
- 28. 如何从字符串中删除所有符号,数字和空格?
- 29. C:删除字符串中的符号
- 30. 从文本中删除标点符号和英文字符
环绕字符串,跟踪两个位置:“写入头”和“读取头”。当读取头碰到标点符号时,无需书写即可向前跳过。否则从读头复制到写头,并向前移动。 – BoBTFish
标准库也被禁止?和std :: string?标点符号只是“。,;:?!”或者它是不是字母数字的东西? – stefaanv
@stefaanv什么都不是字母数字 – lola96