简体   繁体   中英

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?

I'm trying to implement a function that copies characters from the c string source and then stores it into the array destination. I know this is strcpy however I am not allowed to call in any functions and am not allowed to use any local variables. I also have to be able add on a null terminator on the end of it so that the array becomes a c string itself. numChars is the size that the array destination is being limited to. for example if source was "apples" and numChar was 2, the first 3 elements would be 'a', 'p' and '\0'. Below is my attempt, how would I go about this?

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

What you describe is basically strncpy , but your own implementation:

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

}

Something like this should do the trick, you probably should add some error checks as well checking the arguments to the function.

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

Here is my attempt solution:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM