I have a string which is of about 1mb size. The requirement is to reverse the string without allocating another temp string of size 1 MB. I tried the following code
string name = "abcde";
string target = "";
for(int i = name.Length - 1; i >=0; i--)
{
target += name[i];
name = name.Remove(i);
int n = name.Length;
}
but my friend says if we use the function name.Remove(i)
it will return a new string but it is not guaranteed that the old string will be deleted from memory and so there is no guarantee that the size will be reduced. is it true? if so is there any other option available to reverse a string without allocating extra memory?
You can't change it, as it is immutable. What you want is to create a new string, and for this you need new memory. Save this answer.
If we take a look at program to reverse a string or array, all we need to do is swap two characters. The idea is to use XOR for swapping the variable.
Simple Solution:Create a temporary character array say temp[]. Copy alphabetic characters from the given array to temp[]. Reverse temp[] using standard string reversal algorithm. Now traverse input string and temp in a single loop.
Your string "abcde" is a constant in memory. You can't change it, as it is immutable. What you want is to create a new string, and for this you need new memory.
use StringBuilder
you can manupulate with char array, but not with string
, bacause it's immutable
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