Search code examples
cconcatenationoperatorsc-stringsstring-concatenation

Is there any function for prefixing a character to a string and store in the same string?


how do we do the following operation in c? s="#"+s; where s is a string .

I've tried using strncat() but after concatenation answer should be stored in s with prefix "#.


Solution

  • Assuming that s has enough elements, you can add a prefix of one character to s by:

    1. Slide the existing string by one via memmove() (you cannot use strcpy() nor memcpy() because they don't support copying to overlapped region)
    2. Write the character to add to the first element of s.
    #include <stdio.h>
    #include <string.h>
    
    int add_prefix(char* str, char c, size_t bufsz) {
        size_t strsize = strlen(str) + 1;
    
        if (bufsz <= strsize) {
            return -1;
        }
    
        memmove(str + 1, str, strsize); /* +1 for terminating null-character */
        str[0] = c;
        return 0;
    }
    
    int main(void) {
        char s[128] = "hello";
    
        printf("before add_prefix() : %s\n", s);
    
        add_prefix(s, '#', sizeof(s));
        printf("after  add_prefix() : %s\n", s);
    
        return 0;
    }