user1487000
user1487000

Reputation: 1201

Concatenating 0's to string in C

I am trying to add 0's on to the end of a c 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?

Upvotes: 0

Views: 166

Answers (5)

Josh Petitt
Josh Petitt

Reputation: 9579

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

Upvotes: 1

Mahmoud Emam
Mahmoud Emam

Reputation: 1527

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.

Upvotes: 0

Jacob Relkin
Jacob Relkin

Reputation: 163248

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

Upvotes: 0

j_mcnally
j_mcnally

Reputation: 6968

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.

Upvotes: 0

blearn
blearn

Reputation: 1208

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

Upvotes: 2

Related Questions