I've tried so may ways on the Internet to append a character to a char* but none of them seems to work. Here is one of my incomplete solution:
char* appendCharToCharArray(char * array, char a)
{
char* ret = "";
if (array!="")
{
char * ret = new char[strlen(array) + 1 + 1]; // + 1 char + 1 for null;
strcpy(ret,array);
}
else
{
ret = new char[2];
strcpy(ret,array);
}
ret[strlen(array)] = a; // (1)
ret[strlen(array)+1] = '\0';
return ret;
}
This only works when the passed array is "" (blank inside). Otherwise it doesn't help (and got an error at (1)). Could you guys please help me with this ? Thanks so much in advanced !
append(char[] str) method appends the string representation of the char array argument to this sequence. The characters of the array argument are appended, in order, to the contents of this sequence. The length of this sequence increases by the length of the argument.
Use the strncat() function to append the character ch at the end of str. strncat() is a predefined function used for string handling. string.
The simplest solution, lacking any context, is to do: char buffer[ strlen(line) + 1 ]; strcpy(buffer, line); You may be used to using pointers for everything in Java (since non-primitive types in Java are actually more like shared pointers than anything else).
Remove those char * ret
declarations inside if
blocks which hide outer ret
. Therefor you have memory leak and on the other hand un-allocated memory for ret
.
To compare a c-style string you should use strcmp(array,"")
not array!=""
. Your final code should looks like below:
char* appendCharToCharArray(char* array, char a)
{
size_t len = strlen(array);
char* ret = new char[len+2];
strcpy(ret, array);
ret[len] = a;
ret[len+1] = '\0';
return ret;
}
Note that, you must handle the allocated memory of returned ret
somewhere by delete[]
it.
Why you don't use std::string
? it has .append
method to append a character at the end of a string:
std::string str;
str.append('x');
// or
str += x;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With