用C中的多个字符替换字符串(char数组)中的字符

时间:2014-09-09 02:14:48

标签: c arrays string

C不是托管语言,因为我使用了非托管语言,所以已经有一段时间了。我需要创建一个搜索字符数组的代码块,并替换' 2'的所有实例。用' Ba'这很简单,除了现在生成的字符串将比原始字符串更大的事实,所以我需要以某种方式解释这一点,并且我不记得如何做到这一点。

这是尝试编号4,使用指针:

//Move next 150 characters after replacing all 2 with Ba:
    numberread = read(XYZFile, datatoreadWWW, sizeof(datatoreadWWW));
    int y = strlen(datatoreadWWW); //should be 150.
    int additionallength = y;
    i = 0;
    while(i < y) {
      if(datatoreadWWW[i] == '2') {
        additionallength++; //Since we need to replace any '2' with 'Ba', we should add one character for the a.
      }
      i++;
    }
    //And now use additionallength to create the new char array to be placed in WWW, called newstring:
    char newstring[additionallength];
    int j = 0;
    const char *in = datatoreadWWW;
    char *out = newstring;
    while(*in) {
      if (*in == '2') {
    *out++ = 'B';
    *out++ = 'a';
      }
      else {
    *out++ = *in;
      }
      in++;
    }
    *out++ = '\0';

我仍然困惑/坚持这一点,我将垃圾值写入WWW文件,例如&#34; ^ Q&#34;等等。不确定这意味着什么,但它看起来并不正确。

修改:上面的程序现在似乎正在运行。问题是,如果有人将这篇文章作为资源阅读,那我就会在其他长度上添加+1,但这种情况在每次迭代中都会发生,因此每隔这么多字符就会有一个额外的空,空的空间被放入文件中,这是不正确的。无论如何,我认为我们已经了解到在C中工作时检查指针很重要,因为这是实现这一目标的最简单方法。

4 个答案:

答案 0 :(得分:2)

你可以这样做:

  • 通过将'2'的数量添加到字符串的strlen加上一个空终结符
  • 来计算新数组的长度
  • 使用char
  • 分配所需的malloc个数
  • 循环浏览字符串;如果您看到'2',请将'B'后跟'a'添加到输出中;
  • 否则,将当前字符复制到输出。

注意:既然你的字符串是动态分配的,你需要在完成使用后调用free

const char* str = ...
int cnt = strlen(str)+1;
for (const char *p = str ; *p ; cnt += (*p++ == '2'))
    ;
char *res = malloc(cnt);
char *out = res;
const char *in = str;
while (*in) {
    if (*in == '2') {
        *out++ = 'B';
        *out++ = 'a';
    } else {
        *out++ = *in;
    }
    in++;
}
*out++ = '\0';

Demo.

答案 1 :(得分:1)

许多解决方案过于复杂,毫无意义,并且效率低下(例如,当只需要两个扫描时,strlen意味着三次扫描。)

int newlen = 1;

for (char* p = str; *p; p++)
    newlen += *p == '2' ? 2 : 1;

char newstr[newlen];

for (char *p = str, *q = newstr;; p++)
    if (*p == '2')
    {
        *q++ = 'B';
        *q++ = 'a';
    }
    else if (!(*q++ = *p))
        break;

答案 2 :(得分:0)

这是一个如何做到这一点的想法:

  • 计算char数组中'2'的数量并存储在变量中,假设为count

  • 创建一个新的char数组,假设为new_word,其中大小为前一个字符数组加上{2} 的数字存储在count变量中。

  • 从输入词的末尾开始迭代,将字符存储在new_word中。每次达到'2'时,都会插入'a',然后'B',当然,还要正确更新索引。

答案 3 :(得分:0)

你也可以这样试试..

main()
{
char a[]="abcabcabcabcabcabcabc";
char *p;
int i=0,c=0;

for(i=0;a[i];i++)
if(a[i]=='c')
c++;

printf("c=%d\n",c);
p=calloc(sizeof(a)+c,1);

for(i=0;a[i];i++)
{
static int j=0;
if(a[i]=='c')
    {
    *(p+j++)='n';
    *(p+j++)='s';
    }
 else
    {
    *(p+j++)=a[i];
    }
   }
   printf("%s\n",p);
  }