从字符数组中修剪非字母数字字符的功能

Function to trim non, alphabetic, numeric characters from character array

本文关键字:数字字符 功能 字符 数组 修剪      更新时间:2023-10-16

我希望制作一个具有以下原型的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::beginstd::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;
}          

有想法从这里将字符串转换为字符*转换标准字符串转换为常量字符或字符