C++编写一个字符串置换函数

c++编程:
编写一个字符串置换函数 void repstr(char * source, char * str_s, char * str_d),功能是将source 字符串中的str_s子串替换成字符串 str_d

//刚写的code,测试通过,用C++写的
//如果有疑问,欢迎交流
//如果source里有多个str_s字串,那么都会将其替换掉
//这里的条件逻辑,可能有点儿复杂,设定一些状态,用flag表示
//flag: 0表示要往tmp_source里插入字符
//flag: 1表示当前找到了可能是str_s的字串
#include<iostream>
#include<string>
using namespace std;
#define N 1000
void repstr(char * source, char * str_s, char * str_d){
int src_len = strlen(source);
char *tmp_source = new char[N]; //创建一个新串,保存替换后的结果
int flag = 0;
int cur_idx = 0, str_d_idx = 0, str_s_idx = 0, tmp_idx = 0;
while(source[cur_idx] != '\0'){
if(flag == 0 && source[cur_idx] == str_s[0]){
flag = 1;
str_s_idx++;
cur_idx++;
}
if(flag == 1){
if(str_s[str_s_idx] == '\0'){
str_d_idx = 0;
//
while(str_d[str_d_idx]!='\0'){
tmp_source[tmp_idx] = str_d[str_d_idx];
tmp_idx++;
str_d_idx++;
}
str_s_idx = 0;
flag = 0;
}else if(str_s[str_s_idx] == source[cur_idx]){
str_s_idx++;
cur_idx++;
}else if(str_s[str_s_idx] != source[cur_idx]){
flag = 0;
cur_idx = cur_idx - str_s_idx;
str_s_idx = 0;
}
}
if(flag == 0&&source[cur_idx]!='\0'){
tmp_source[tmp_idx] = source[cur_idx];
tmp_idx++;
cur_idx++;
}
}
tmp_source[tmp_idx] = '\0';
tmp_idx = 0;
while(tmp_source[tmp_idx]!='\0'){
source[tmp_idx] = tmp_source[tmp_idx];
tmp_idx++;
}
source[tmp_idx] = 0;

delete tmp_source;
}
int main(){
char source[1000] = "word hellonicehelotoyouhellowhy";
cout<<source<<endl;
char *src_s = "hello";
char *tar_s = "ChinaFootball";
repstr(source, src_s, tar_s);
cout<<source<<endl;
return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-01-11
//字符串替换函数,在字符串 string 中查找 source, 找到则替换为destination,找不到则返回NULL
static char * replace_string (char * string, const char * source, const char * destination )
{
char* sk = strstr (string, source);
if (sk == NULL) return NULL;

char* tmp;
size_t size = strlen(string)+strlen(destination)+1;

char* newstr = (char*)calloc (1, size);
if (newstr == NULL) return NULL;

char* retstr = (char*)calloc (1, size);
if (retstr == NULL)
{
free (newstr);
return NULL;
}

snprintf (newstr, size-1, "%s", string);
sk = strstr (newstr, source);

while (sk != NULL)
{
int pos = 0;
memcpy (retstr+pos, newstr, sk - newstr);
pos += sk - newstr;
sk += strlen(source);
memcpy (retstr+pos, destination, strlen(destination));
pos += strlen(destination);
memcpy (retstr+pos, sk, strlen(sk));

tmp = newstr;
newstr = retstr;
retstr = tmp;

memset (retstr, 0, size);
sk = strstr (newstr, source);
}
free (retstr);
return newstr;

}
第2个回答  2015-01-11
能用 C 语言实现的功能,没有必要非去用 C++ 实现。追问

这是课后题来的,想看看怎样用C++解决

相似回答