替换字符串中出现的某段字符串的C语言和C++实现方式

C语言实现方式

使用了循坏来重复替换操作,直到无法再找到需要替换的子串为止。具体实现如下:

#include <stdio.h>
#include <string.h>

void replace_all(char *str, const char *orig, const char *rep) {
    
    
	// 1. 定义一个静态变量buffer来存储替换后的字符串
    static char buffer[4096];
    // 2. 使用指针p指向原始字符串str,并获取orig和rep的长度。
    char *p = str;
    size_t orig_len = strlen(orig);
    size_t rep_len = strlen(rep);
    // 3. 在循环中中,使用strstr函数查找orig在p指向的位置开始之后第一次出现的位置、
    while ((p = strstr(p, orig))) {
    
    
        // 如果找到了,则将该位置之前的部分拷贝到buffer中,
        strncpy(buffer, str, p - str);
        buffer[p - str] = '\0';
        // 并使用sprintf函数将替换后的新子串和剩余字符串拼接起来,
        sprintf(buffer + (p - str), "%s%s", rep, p + orig_len);
        // 最后再将结果拷贝回原始字符串中。
        strcpy(str, buffer);
        // 4.更新指针p的位置,使其指向新的字符串中下一个需要替换的子串之后的位置,
        // 并重复步3直到无法再找到需要替换的子由为止
        p = str + (p - str) + rep_len;
    }
}

int main() {
    
    
    char str[100] = "{app}/set/request/database/model/{app}";
    replace_all(str, "{app}", "myapp");
    printf("%s", str);
    return 0;
}

这种实现方式可以替换换所有出现的 app ,而不仅仅是第一个匹配的子串,但也需要注意,如果原始字符串str和替换后的字符串rep的总长度超过了buffer的大小(4096),则会导致缓冲区溢出的问题,因此在实际使用时,可能需要根据具体情况修改bufer的大小或者采用其他更加安全的方式来进行字符串替换操作。

C++实现方式

#include <iostream>
#include <string>

// 原始字符串str、需要替换的子串orig和替换成的子串rep。
void replace_str(std::string& str, const std::string& orig, const std::string& rep) {
    
    
	size_t pos = 0;
	// 调用字符串的find函数来查找orig在str中的位置,
    while ((pos = str.find(orig, pos)) != std::string::npos) {
    
    
    	// 如果找到了,则使用replace函数将找到的orig替换为rep。
        str.replace(pos, orig.length(), rep);
        // 然后更新pos变量,继续在更新后的字符串中查找下一个orig出现的位置,并重复替换操作,
    	// 直到无法再找到orig为止。最终返回替换完成后的字符串。
 		pos += rep.length();
    }
}

int main() {
    
    
    std::string str = "{app}/set/request/database/model/{app}";
    replace_str(str, "{app}", "myapp");
    std::cout << str << std::endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43577613/article/details/130436264