串替换,实现字符串替换操作

不调用库函数,自己实现字符串替换操作,函数原型为:

int str_replace(const char *in, char *out, int outlen, const char *oldstr, const char *newstr);

参数说明:

in, 原始字符串,保持不变

out, 存放替换结果的字符串

outlen,out空间的大小

oldstr,要替换的旧字符串

newstr,替换成的新字符串

函数返回成功替换的次数,即有多少个子串被成功替换

在替换过程中,任何情况下所得字符串(及结束符)不应该超过 outlen,如果某次替换所得字符串的长度超过 outlen,则不进行这次替换操作,整个替换操作结束。如:
原始串为 “aaabbbccc”,outlen 为14, oldstr 为 “c”,newstr 为 “333” 时,两次替换后得 “aaabbb333333c”,此时字符串占用空间为14字节。
如果再进行替换,则会超出 out 所占用的空间,所以停止替换操作。此时函数应该返回 2, out指向的串为 “aaabbb333333c”
再如:原始串为 “aaabbbccc”,outlen 为10, oldstr 为 “bb”,newstr 为 “123456”,进行替换后所得的串应该为 “aaa123456” (长度为9)与结束符一共占 10 个字节,此时函数应该返回 1。

#include "dsstring.h"
#include <stdio.h>
#include <stdlib.h>
int get_len(const char* s)
{
    int i = 0;
    while (s[i]) {
        i++;
    }
    return i;
}
int str_replace(const char* in, char* out, int outlen, const char* oldstr, const char* newstr)
{
    int count_times = 0;
    int i;
    int j = 0;
    int k;
    int flag = 0;
    for (i = 0; outlen > 1 && in[i] != 0; i++) {
        if (in[i] != oldstr[0]) {
            out[j] = in[i];
            j++;
            outlen--;
            continue;
        } else {
            flag = 0;
            for (k = 0; oldstr[k] != 0; k++) {
                if (in[k + i] != oldstr[k]) {
                    break;
                } else {
                    if (k == (get_len(oldstr) - 1)) {
                        if (outlen > get_len(newstr)) {
                            i += k;
                            flag = 1;
                        }
                    }
                }
            }
            if (flag == 1) {
                count_times++;
                for (k = 0; newstr[k] != 0; k++) {
                    out[j] = newstr[k];
                    j++;
                    outlen--;
                }
            } else {
                out[j] = in[i];
                j++;
                outlen--;
            }
        }
    }
    out[j] = 0;
    return count_times;
}

如果有更好的方法或者以上程序有任何错误,欢迎讨论。

猜你喜欢

转载自blog.csdn.net/weixin_45454859/article/details/105427145