簡體   English   中英

如何從 c 字符串復制到數組中,然后限制返回的數量,同時還在末尾添加 null 終止符?

[英]How can I copy from a c string into an array and then limit the amount returned while also adding a null terminator onto the end?

我正在嘗試實現一個 function ,它從 c 字符串源復制字符,然后將其存儲到數組目標中。 我知道這是 strcpy 但是我不允許調用任何函數,也不允許使用任何局部變量。 我還必須能夠在其末尾添加 null 終止符,以便數組本身成為 c 字符串。 numChars 是數組目標被限制的大小。 例如,如果 source 是“apples”並且 numChar 是 2,則前 3 個元素將是 'a'、'p' 和 '\0'。 以下是我的嘗試,我將如何 go 關於這個?

void copyWord(char * destination, const char * source, int numChars){
    
    while(*destination != numChars){
        *destination = *source;
        destination++;
        source++;
    }
    destination[numChars] = '\0';
}

您描述的基本上是strncpy ,但是您自己的實現:

void copyWord(char *destination, const char *source, int destSize) {

    if ((destination == nullptr) || (destSize <= 0)) {
        return;
    }

    while ((destSize > 1) && (*source)) {
        *destination = *source;
        destination++;
        source++;
        destSize--;
    }

    // destSize is at least 1, so this is safe
    *destination = '\0';

}

像這樣的東西應該可以解決問題,您可能應該添加一些錯誤檢查以及檢查 arguments 到 function。

void copyWord(char * destination, const char * source, int numChars)
{
    while(numChars-- && *source) 
    {
        *destination++ = *source++;
    }
    *destination = '\0';
}

這是我的嘗試解決方案:

void copyWord(char * destination, const char *source, int numChars){
    if(!numChars){
         *destination = '\0';
         return;
    }
    while(*source != NULL && numChars --){
        *destination = *source;
        destination++;
        source++;
    }
    *destination = '\0';
}

暫無
暫無

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

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