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 "#.
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;
}
For starters the character array that stores the source string should be large enough to be able to append one more character.
Here is a demonstrative program.
#include <stdio.h>
#include <string.h>
int main( void )
{
char s[7] = "Hello";
memmove( s + 1, s, strlen( s ) + 1 );
s[0] = '#';
puts( s );
}
The program output is
#Hello
A more general approach can look the following way
#include <stdio.h>
#include <string.h>
char * append_prefix( char s[], const char *prefix )
{
size_t n = strlen( prefix );
if (n != 0)
{
memmove( s + n, s, strlen( s ) + 1 );
memcpy( s, prefix, n );
}
return s;
}
int main( void )
{
char s[7] = "Hello";
puts( append_prefix( s, "#" ) );
}
Using the function append_prefix you can append any string before another string provided that the result character array has enough space.
Kind of depends on the application. If you are writing some string library, some search algorithm or other performance-critical stuff, then you can fiddle around with memmove as shown in other answers, or more likely some custom, alignment-based algorithm.
But unless you have such extreme RAM usage or performance requirements, then you should probably treat all strings as "immutable" (basically read-only) and just create a new one. Which is "good enough" for the average C application.
In which case it simply goes like:
char s[] = "hello";
char new_s [LARGE_ENOUGH] = "#";
strcat(new_s, s);
Where "LARGE_ENOUGH" could be something like 2 + strlen(s).