从数组中删除找到空格和标点符号的字符 [英] Remove character from array where spaces and punctuation marks are found
问题描述
在我的程序中,我检查整个cstring,如果发现任何空格或标点符号,只是添加空字符到该位置,但是complilor给我一个错误:空字符常量。
In my program, I am checking whole cstring, if any spaces or punctuation marks are found, just add empty character to that location but the complilor is giving me an error: empty character constant.
请帮助我,在我的循环中我检查这样
Please help me out, in my loop i am checking like this
if(ispunct(str1[start])) {
str1[start]=''; // << empty character constant.
}
if(isspace(str1[start])) {
str1[start]=''; // << empty character constant.
}
这是我的错误,请纠正我。
This is where my errors are please correct me.
例如, str ,, ing,
输出应为 string
。
推荐答案
尝试这个(显式地请求 cstring
/ p>
Try this (as you asked for cstring
explicitly):
char str1[100] = "str,, ing";
if(ispunct(str1[start]) || isspace(str1[start])) {
strncpy(str1 + start, str1 + start + 1, strlen(str1) - start + 1);
}
好吧,这只是在纯粹 c 语言,有更有效的解决方案(看看@Michael Plotke 的详细答案)。
Well, doing this just in pure c language, there are more efficient solutions (have a look at @MichaelPlotke's answer for details).
但您也明确要求 c ++ ,我建议如下的解决方案:
But as you also explicitly ask for c++, I'd recommend a solution as follows:
注意 可以使用标准c ++算法进行'plain'c-样式字符数组。你只需要将你的谓词条件移除到一个小的帮助函数中,并使用 std :: remove_if()
算法:
Note you can use the standard c++ algorithms for 'plain' c-style character arrays also. You just have to place your predicate conditions for removal into a small helper functor and use it with the std::remove_if()
algorithm:
struct is_char_category_in_question {
bool operator()(const char& c) const;
};
后来使用:
#include <string>
#include <algorithm>
#include <iostream>
#include <cctype>
#include <cstring>
// Best chance to have the predicate elided to be inlined, when writing
// the functor like this:
struct is_char_category_in_question {
bool operator()(const char& c) const {
return std::ispunct(c) || std::isspace(c);
}
};
int main() {
static char str1[100] = "str,, ing";
size_t size = strlen(str1);
// Using std::remove_if() is likely to provide the best balance from perfor-
// mance and code size efficiency you can expect from your compiler
// implementation.
std::remove_if(&str1[0], &str1[size + 1], is_char_category_in_question());
// Regarding specification of the range definitions end of the above state-
// ment, note we have to add 1 to the strlen() calculated size, to catch the
// closing `\0` character of the c-style string being copied correctly and
// terminate the result as well!
std::cout << str1 << endl; // Prints: string
}
查看这个可编译的工作示例此处。
See this compilable and working sample also here.
这篇关于从数组中删除找到空格和标点符号的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!