how can i change the string?  
Author Message
merwy





PostPosted: Visual C# General, how can i change the string? Top

hi all

i'm coding an evaluator program.in these program i'm taking a equation with x parameter.the equation is str1 and the x parameter is ara.ara is char.the code is below.but i cant replace the x parameter with ara.where's the mistake

while (index < str1.Length)

{

c = str1.Substring(index, 1);

if (c=="x")

{

str1.Replace('x',ara);

MessageBox.Show(str1);

}

index++;

}



Visual C#16  
 
 
Peter Ritchie





PostPosted: Visual C# General, how can i change the string? Top

The String class is immutable, you can't change it's contents. String.Replace returns a new instance of a string. Do this instead:
str1 = str1.Replace('x'.ara);

 
 
James Curran





PostPosted: Visual C# General, how can i change the string? Top

Also, the rest of the code snippet (manually searching the string for an "X") is pointless. The replace it going to do it's own search (and not replace anything of no "x" is found). The entire thing can be replace with just

str1 = str1.Replace("x", ara);