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 "#.
Assuming that s
has enough elements, you can add a prefix of one character to s
by:
memmove()
(you cannot use strcpy()
nor memcpy()
because they don't support copying to overlapped region)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;
}