c - 需要优化如下split()函数代码

标签 c optimization cstring

问题陈述:

想要一个优化的分割函数,它将搜索字符串中的给定字符,并将字符串分割成字符之前和之后的 2 个子字符串

示例:

s1 = strdup("XYZ@30");
s2 = split(s1,"@");
Should get following output.
s1 = "XYZ"    
s2 = "30"

我已经写了下面的 split(),但是有人可以帮我优化它吗?

char * split(char *str1, char *ch)
{
    int i=0;
    char *str2;
    if(!(str1 && ch))
        return NULL;
    else
    {
        str2 = strdup(str1);
        while('\0'==str2)
        {
            if(*str2==*ch)
            {
                i++;
                str1[i]='\0';
                return (++str2);//If the ch is last in str1, str2 can be NULL    
            }
            str2++;
        }
    }
    return NULL;
}

最佳答案

不要使用strdup;只需让 str2 指向分割字符之后的字符即可。

关于c - 需要优化如下split()函数代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23761747/

相关文章:

c - 我分配内存错误吗?

c++ - 用于平铺矩阵乘法的 AVX 内在函数

python - 将零移动到末尾 : Why does my Python Code fail the test in CodeWars?

c++ - 重写 Java 的 String.toUpperCase() 返回空字符数组

C++ string() 与 c 字符串的比较。为什么这行得通?

使用 sscanf 检查空格长度

c - 胡乱使用 *nix API 会导致文本文件出现乱码

java - 通过 jni NewByteArray 在何处释放分配的内存

c - fd 泄漏,自定义 Shell

optimization - BigCommerce 和开发/优化