簡體   English   中英

使用 for 循環將字符附加到 C 中的字符串中

[英]Appending chars into a String in C with a for loop

我仍然是 C 的新手,所以如果下面有任何錯誤,請原諒我。 我已經在網上搜索過,但沒有任何幫助。

現在,我有以下代碼:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

 void appendStr (char *str, char c)
  {
    for (;*str;str++); // note the terminating semicolon here. 
    *str++ = c; 
    *str++ = 0;
  }

int main(){
    char string[] = "imtryingmybest";
    char result[] = "";
    
    for(int i = 0; i < strlen(string); i++){
        if(i >= 0 && i <= 3){
            appendStr(result, string[i]);
        }
    }
    printf("%s", result);
}

基本上,我試圖result名為string的前 4 個字符添加到 for 循環中。 我上面的代碼不起作用。 我已經嘗試過使用strcatstrncat ,但它們都不適合我。 當我使用

strcat(result, string[i]);

它返回一個錯誤,指出無法讀取 memory。

我知道在這個例子中,如果我這樣做可能會更容易

appendStr(result, string[0]);
appendStr(result, string[1]);
appendStr(result, string[2]);
appendStr(result, string[3]);

但是,我使用 for 循環的原因在此示例中無法解釋。

總而言之,如果有人能向我解釋如何將 append 單個字符轉換為 for 循環中的字符串,我將不勝感激。

以下代碼不使用您的方法,但成功地將前 4 個字符附加到result

#include <stdio.h>
#include <string.h>

int main()
{
  // declare and initialize strings
  char str[] = "imtryingmybest";
  char result[5];    // the 5th slot is for \0 as all strings are null terminated

  // append chars to result
  strncat(result, str, 4);
//          ^      ^   ^
//          |      |   |- number of chars to be appended
//          |      | - string to be appended from
//          | - string to append to

  // print string
  printf("result: %s\n", result);

  return (0);
}

上面的結果是想要的:

>> gcc -o test test.c
>> ./test
result: imtr

讓我知道是否有任何不清楚的地方,以便我進一步詳細說明

字符串被結果緩沖區溢出破壞了。

appendStr 只能執行一次。 下一次 strlen(string) 將返回 0。因為 *str++ = 0; 已寫入字符串空間。

結果緩沖區只有 1 個字節空間,但您在 appendStr 調用中向其寫入 2 個字節。 第二個字節將破壞字符串空間。

我建議使用 gdb 進行調試。

嘗試擺脫魔術數字

#define BUFF_SIZE 10 // define some bytes to allocate in result char array
#define COPY_COUNT 4 // count of chars that will be copied 

int main(){
    char string[] = "imtryingmybest";
    char result[BUFF_SIZE] {}; // allocate some chunk of memory
    
    for(size_t i = 0; i < strlen(string); i++){
        if(i < COPY_COUNT){
            appendStr(result, string[i]);
        }
    }
    printf("%s", result);
}

我展示了解決方案代碼 Paul Yang 展示了問題

正如其他人指出的那樣,代碼在分配目標字符串時有一個簡單的錯誤。
在聲明數組而不指定其大小時,編譯器會通過其初始化程序推斷它,在您的情況下,這意味着 0 + NULL 字符。

char result[] = ""; // means { '\0' };

但是,我認為這里更大的問題是您正在有效地編寫 Schlemiel 代碼。
C 字符串有一個嚴重的缺點,即它們不存儲長度,使得必須到達字符串末尾的函數在時間復雜度 O(n) 上呈線性關系。
您已經知道這一點,如您的 function appendStr()所示

在開始在循環中附加字符或字符串之前,這不是一個嚴重的問題。
在循環的每次迭代中, appendStr()到達字符串的最后一個字符,並擴展字符串,從而使下一次迭代變慢一些。
實際上它的時間復雜度是 O(n²)
當然,對於小字符串或迭代次數很少的循環來說,這並不明顯,但如果數據規模擴大,這將成為一個問題。

為避免這種情況,您必須考慮字符串的增長大小。
我修改appendStr()以顯示現在它從 result 的最后一個元素開始

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

 void appendStr (char *str, char c, char *orig)
{
    printf("i: %ld\n", str - orig);
    for (; *str; str++); // note the terminating semicolon here. 
    *str++ = c; 
    *str++ = 0;
}

int main()
{
    char string[32] = "imtryingmybest";
    char result[32] = "";
    
    for(int i = 0; i < strlen(string); i++) {
        if(i >= 0 && i <= 3) {
            // I'm passing a pointer to the last element of the string
            appendStr(&result[i], string[i], result);
        }
    }
    printf("%s", result);
}

你可以在這里運行它https://onlinegdb.com/HkogMxbG _

更多關於畫家施萊米爾的信息
https://www.joelonsoftware.com/2001/12/11/back-to-basics/
https://codepen.io/JoshuaVB/pen/JzRoyp

暫無
暫無

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

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