Ok, so I have a char stringA and char stringB, and I want to be able to insert stringB into stringA at point x.
char *stringA = "abcdef";
char *stringB = "123";
with a product of "ab123cdef"
does anyone know how to do this? Thanks in advance
One can use the StringBuffer class method namely the insert() method to add character to String at the given position. This method inserts the string representation of given data type at given position in StringBuffer. Syntax: str.
std::string::insert() in C++ insert() is used to insert characters in string at specified position. It supports various syntaxes to facilitate same, here we will describe them. Syntax 1: Inserts the characters of str starting from index idx.
Use the strncat() function to append the character ch at the end of str. strncat() is a predefined function used for string handling. string.
A simple solution to append a character to the end of a string is using the string concatenation operator (+) . This creates a new instance of the string, since strings in Java are immutable and cannot be modified.
char * strA = "Blahblahblah", * strB = "123", strC[50];
int x = 4;
strncpy(strC, strA, x);
strC[x] = '\0';
strcat(strC, strB);
strcat(strC, strA + x);
printf("%s\n", strC);
Explanation:
Hope that helps.
Remark: remember to make strC long enough to contain both strA and strC, otherwise you'll produce a segmentation fault. You may do this by declaring the string as an array, like in my example.
stringA and stringB are both pointers - they contain the starting address for a blob of memory. The memory they are pointing to contain continuous strings of characters: "abcdef" and "123" respectively. Since strings are contiguous blocks memory (meaning that the memory location of a given character is one byte after the previous) you can't insert more characters into the middle of a string without first moving some characters. In your case you can't even really do this, since the amount of memory allocated for each string is exactly large enough to hold JUST that string (ignoring padding).
What you are going to have to do is copy the strings to another block of memory, one that you have allocated for that purpose, and copy them so that the second string starts x characters into the first string.
Several other SO users have posted code-solutions but I think you should try and find the exact solution on your own (and hopefully my high-level explanation of what's going on will help).
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