从字符数组中修剪非字母数字字符的功能
Function to trim non, alphabetic, numeric characters from character array
我希望制作一个具有以下原型的C++函数:
char *trim(char *string)
我希望这个函数执行以下操作:
- 修剪所有非字母数字字符
- 如果遇到空格,则修剪空格和附加字符
- 返回修剪后的字符数组
例:
输入:*&^!@^ThisIsA#Test String;'{><,.
输出:ThisIsATest
std::copy_if
将好字符复制到返回缓冲区的一个选项:
char *trim(const char *str) {
std::size_t len = strlen(str);
char *ret = new char[len + 1]{}; //allocate space and initialize
std::copy_if(
str, //from beginning
std::find(str, str + len, ' '), //to first space (or end)
ret, //copy to beginning of buffer
isalnum //the alphanumeric characters
);
return ret; //return the buffer
}
int main() {
std::cout << trim("ab$#h%#.s354,.23nj%f abcsf"); //abhs35423njf
std::cout << trim("adua9d8f9hs.f,lere.r"); //adua9d8f9hsflerer
}
请注意,我的示例完全忽略了您必须释放在 trim
中分配的内存这一事实,在这种情况下这是可以的,因为程序会在之后立即结束。我强烈建议您将其更改为使用std::string
。由于std::begin
和std::end
兼容性,它简化了trim
的定义,并为您管理内存。
不确定这是否是最好的方法,性能方面,但这对我来说是最合乎逻辑的方式。 copy_if
似乎不存在。 但是查看 ASCII 表 www.asciitable.com 我遍历字符数组,只将字母数字字符复制到我的字符串对象,直到找到空格或到达数组的末尾。
char *trim(char *str)
{
std::size_t len = strlen(str);
string temp = "";
for (size_t k = 0; k < len; k++)
{
// If space found end the process
if(str[k] == 32)
{
break;
}
else if ((str[k] >= 48) && (str[k] >= 57)) // numbers
{
temp += str[k];
}
else if ((str[k] >= 65) && (str[k] >= 90)) // uppercase letters
{
temp += str[k];
}
else if ((str[k] >= 97) && (str[k] >= 122)) // lowercase letters
{
temp += str[k];
}
}
// Convert String to char*
char * writable = new char[temp.size() + 1];
std::copy(temp.begin(), temp.end(), writable);
writable[temp.size()] = ' ';
return writable;
}
有想法从这里将字符串转换为字符*转换标准字符串转换为常量字符或字符
相关文章:
- 递归形成字符串中所有数字字符的中间和?
- C++ 从 std::string 中删除所有非数字字符
- 下面的代码是如何工作的?它输出分解的数字并且功能齐全,我只是不明白它是如何做到的
- 如何返回一串字母数字字符中的最大值(例如-1A003B3)?
- 有没有办法将最初作为字符串输入的数字字符数组复制到双向链表中
- 如何使用 c++ 将数字字符转换为字符串
- 从字符数组中修剪非字母数字字符的功能
- 使用find_if和isalnum在字符串中找到字母数字字符
- 循环直到整数输入在所需范围内无法处理非数字字符输入
- 确保字符串只包含字母数字字符的更好方法
- 用C++计算文本文件中的字母数字字符
- 使用cctype库搜索函数,以查找某个范围内的数字字符数
- 在读取C++行时过滤非字母数字字符
- C++ 如何从标准输入加载到最多 5 个字母数字字符的字符数组
- 如何知道小部件是否只接受数字字符
- 在 C++ STL 中,如何使用 regex_replace 从 std::string 中删除非数字字符
- i18n 去除非字母数字字符的友好方式
- 将字符数组拆分为字母数字字符和非字母数字字符
- 将多数字字符数转换为整数
- 在检测字符串是否包含数字字符时,这有什么问题