使用反向for循环替换C中字符串的结尾

我正在尝试使用for向后for循环对原始字符串的每个元素进行迭代来替换字符串的最后一部分,并将第一个(最后一个元素,因为我在for循环中向后进行迭代)分配给字符串{ {1}},其余部分在计数器的值低于15时,从字符串scl = "SCL_10m.tif"中获取所有字符,并将它们分配给string。 但是最后结果是:

newString

与我的预期结果不同:

The old string was: S2_2018_08_09_B02_10m.tif
The new string is S2_2018_08_09_B0old string:

我不知道发生了什么。由于它与原始字符串的大小相同,因此应该迭代The new string is S2_2018_08_09_SCL_10m.tif 的所有元素。我在C中检查了一些替换字符串函数,但是我想实现一些可帮助我快速解决String问题中特定替换子字符串的功能。

在C中使用String进行交易非常复杂,我仍在学习有关它的一些理论,例如:null Byte等。来自JavaScript,Python和Ruby,这些功能中的更多功能已在某个标准库中实现,我感到非常困难,同时也有助于我从头开始实现此类算法以解决我的特定问题码。 感谢您对以下代码中发生的事情有任何想法或提示:

newString
jing135985 回答:使用反向for循环替换C中字符串的结尾

char *func1(char *new,const char *src,const char *repl)
{
    size_t src_len,repl_len;

    if(src && repl)
    {
        src_len = strlen(src);
        repl_len = strlen(repl);
        if(src_len >= repl_len)
        {
            new[src_len] = 0;
            while(repl_len)
            {
                new[--src_len] = repl[--repl_len];
            }
            if(src_len)
            {
                while(--src_len)
                {
                    new[src_len] = src[src_len];
                }
            }
        }
    }
    return new;
}

char *func2(char *new,const char *repl,size_t nchars)
{
    //last nchars only (inluding the nul char)
    size_t src_len,repl_len;

    if(new &&src && repl)
    {
        new[--nchars] = 0;
        src_len = strlen(src);
        repl_len = strlen(repl);
        if(src_len >= repl_len)
        {
            while(repl_len && nchars)
            {
                new[--nchars] = repl[--repl_len];
                --src_len;
            }
            if(src_len && nchars)
            {
                while(--src_len && --nchars)
                {
                    new[nchars] = src[src_len];
                }
            }
        }
    }
    return new;
}

int main()
{
    char *string =  "S2_2018_08_09_B02_10m.tif";
    char *repl =  "SCL_10m.tif";
    char new[256];
    printf("func1 - new = \"%s\",src = \"%s\",repl = \"%s\"\n",func1(new,string,repl),repl);
    printf("func2 - new = \"%s\",func2(new,repl,15),repl); 
    printf("func2 - new = \"%s\","123456789_SCL_10m.tif",repl); 
    return 0;
}
本文链接:https://www.f2er.com/3131751.html

大家都在问