Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing a string without creating extra memory

Tags:

c#

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?

like image 277
Jeeva Avatar asked Jul 05 '12 08:07

Jeeva


People also ask

How can a string be reversed without affecting memory size?

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.

How do I reverse a string without making a new string?

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.

How do you reverse a string without affecting special characters?

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.


2 Answers

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.

like image 179
Martin1921 Avatar answered Sep 28 '22 09:09

Martin1921


use StringBuilder you can manupulate with char array, but not with string, bacause it's immutable

like image 41
burning_LEGION Avatar answered Sep 28 '22 09:09

burning_LEGION