簡體   English   中英

用C中的多個字符替換字符串(char數組)中的字符

[英]Replacing a character in a string (char array) with multiple characters in C

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';

而且我對此仍然感到困惑/困惑,我正在將垃圾值寫入諸如“ ^ Q”之類的WWW文件中。 不知道那意味着什么,但似乎並不正確。

編輯:上面的程序似乎現在正在工作。 問題是,如果有人將這篇文章作為資源閱讀,我會在extendedlength上加上+1,但是這種情況在每次迭代中都會發生,因此每隔這么多字符,就會在文件中放入一個額外的空,空空間,這是不正確的。 無論如何,我認為我們已經學到了在使用C語言進行操作時檢查指針很重要,因為這是完成此操作的最簡單方法。

您可以這樣做:

  • 通過將字符串的strlen'2'的數量加上一個用於空終止符的數字來計算新數組的長度
  • 使用malloc分配所需的char
  • 循環遍歷您的字符串; 如果看到'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';

演示。

許多解決方案過於復雜,毫無意義地冗長且效率低下(例如,當只需要兩次掃描時,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;

這里是一個想法如何做到這一點:

  • 計算 char數組中'2'的數目並存儲在變量中,例如count

  • 創建一個新的char數組,假設為new_word ,其值為先前的char數組大小加上 count變量中存儲的2的 count

  • 從輸入單詞的末尾開始迭代,將字符存儲在new_word 每次達到“ 2”時,都先插入“ a”,然后再插入“ B”,當然還要正確地更新索引。

您也可以這樣嘗試。

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);
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM