0

我正在尝试用 C 编写代码,它将接受一个字符串,检查每个字符的特定字符(调用它'x'),如果字符是'x',则将其更改为多个字符(如"yz")。这是我的尝试,假设缓冲区和替换是定义的字符数组(即char buffer[400] = jbxyfgextd...; char replace[250];

  int j = 0;
  for (j = 0; j < 110; j++) {
    if (buffer[j]=='x') {
      int len = strlen(replace);
      replace[len] = 'y';
      replace[len+1] = 'z';
    }
    else {
      replace[j]=buffer[j];
    }
  }

当我运行它时,我得到一些y's 和z's,但它们不是背靠背的。是否有任何程序/功能可以轻松做到这一点?

4

2 回答 2

2

因为索引buffer[]replace[]数组不同。分别使用两个索引。

在您的代码表达式中:replace[j] = buffer[j]; 是错误的。您可以像这样更正它:

 else {
      int len = strlen(replace);
      replace[len]=buffer[j];
 }

但是要使用strlen(),数组replace[]应该是 nul\0终止的。(声明替换为char replace[250] = {0}

编辑:

要编写更好的代码,请使用我上面建议的两个分隔索引——代码将变得高效和简化。

int bi = 0;  // buffer index 
int ri = 0;  // replace index 
for (bi = 0; bi < 110; bi++) {
    if (buffer[bi] == 'x') {      
      replace[ri++] = 'y';
      replace[ri] = 'z';
    }
    else {
      replace[ri] = buffer[bi];
    }
    replace[++ri] = '\0'; // terminated with nul to make it string   
}
于 2013-09-05T04:32:37.253 回答
0
#include <iostream>
#include <string>
#include <cstring>

int main ( int argc, char *argv[])
{

  // Pass through the array once counting the number of chars the final string
  // will need then allocate the new string

  char buffer[] = "this x is a text test";

  char replacement[] = "yz";
  unsigned int replaceSize = strlen(replacement);

  unsigned int bufferSize = 0;
  unsigned int newSize = 0;

  // calculate the current size and new size strings
  // based on the replacement size

  char *x = buffer;
  while (*x)
  {
    if ( *x == 'x' )
    {
      newSize+=replaceSize;
    }
    else
    {
      ++newSize;
    }
    ++x;
    ++bufferSize;
  }

  // allocate the new string with the new size 
  // and assign the items to it
  char *newString = new char[newSize];
  unsigned int newIndex = 0;
  for ( unsigned int i = 0; i < bufferSize; ++i )
  {
    if ( buffer[i] == 'x' )
    {
      for ( unsigned int j = 0; j < replaceSize ; ++j )
      {
        newString[newIndex++] = replacement[j];
      }
    }
    else
    {
      newString[newIndex++] = buffer[i];
    }
  }

  std::string originalS ( buffer );
  std::string newS ( newString );

  std::cout << "Original: " << originalS << std::endl;
  std::cout << "New: " << newS << std::endl;

  delete newString;

}
于 2013-09-05T05:03:35.347 回答