简体   繁体   中英

Concatenating 0's to string in C

I am trying to add 0's on to the end of ac string such that the total length is 100.

So for example if string is "hi", I wanna add 98 0's.

What's the easiest way to do this?

Malloc memory for 100 characters. Memset all characters to '0' and then set the first 2 characters to hi.

Cue the one liners!

// this does exactly what you want
// first two chars are 'h' and 'i', all the rest are 0.
char myString[100] = {'h', 'i'};

Try something like this:

static inline char *newPaddedStringToLength(const char *string, const char character, unsigned length) {
    if(strlen(string) >= length) return NULL;

    char *newString = malloc(sizeof(char) * length);
    memset(newString, character, length);
    for(unsigned i = 0; i < strlen(string); ++i) {
        newString[i] = string[i];
    }
    return newString;
}

char *string = "Blah";
char *padded = newPaddedStringToLength(string, '0', 100);


//...

if(padded) free(padded);

1) can i suggest you use NULL instead?

2) There are no strings in C.

I assume your working on some sort of binary format.

If you have a char array that you want to be 100 chars long a char is represented as a byte in ascii.

You can alloc a char array that is 100 bytes long

and write the h and i bytes and you should have 98 null bytes. If you actually want zeros write 0 bytes to the rest.

You could use a loop.

string name[100] = {'h', 'i'}'

This is the easiest way ti initialize a string.

Here the compiler will but the first 2 chars with h and i and the others with null chars ( \\0 or 0 ) both are the same.

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