另一个在C替换字符串的一部分最佳方式吗? [英] Best way to replace a part of string by another in c?

查看:101
本文介绍了另一个在C替换字符串的一部分最佳方式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  如何用C代替子?

我试图寻找这个问题的一个更好的解决方案。有codeS可用,但全部为C ++。不要忘记,这是在Java中非常简单和基本的。我想在C伟大的最佳解决方案?

I have tried looking for a better solution for this problem. There are codes available but all for C++. Not to forget this is very simple and basic in Java. I wanted a great optimal solution in C?

任何帮助将大大AP preciated!
谢谢!

Any help will be greatly appreciated! Thanks!

推荐答案

在谷歌找到简单的解决方案:<一href=\"http://www.linuxquestions.org/questions/programming-9/replace-a-substring-with-another-string-in-c-170076/\" rel=\"nofollow\">http://www.linuxquestions.org/questions/programming-9/replace-a-substring-with-another-string-in-c-170076/

Simple solution found on google: http://www.linuxquestions.org/questions/programming-9/replace-a-substring-with-another-string-in-c-170076/

编辑:以你的标准考虑在内,我已经编辑了链接code这样:

Taking your specification into account, I've edited the code in the link to this:

char *replace_str(char *str, char *orig, char *rep, int start)
{
  static char temp[4096];
  static char buffer[4096];
  char *p;

  strcpy(temp, str + start);

  if(!(p = strstr(temp, orig)))  // Is 'orig' even in 'temp'?
    return temp;

  strncpy(buffer, temp, p-temp); // Copy characters from 'temp' start to 'orig' str
  buffer[p-temp] = '\0';

  sprintf(buffer + (p - temp), "%s%s", rep, p + strlen(orig));
  sprintf(str + start, "%s", buffer);    

  return str;
}

这篇关于另一个在C替换字符串的一部分最佳方式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆