Click here to Skip to main content
15,899,754 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi Friends,

I want to replace values in existing string in c#

For eg : OldString = A=3;B=2;C=5 and new value B=6;C=7; then output should be A=3;B=6;C=7;


Please suggest solution
Posted

Refer this

C# Replace string examples[^]

Example:
C#
string first="B=2";
string final=first.Replace("2","6");

Regards..:)
 
Share this answer
 
v2
Comments
abbaspirmoradi 4-Sep-13 7:20am    
If we have no idea B equal with (B=? ) then this is not work..
Thanks7872 4-Sep-13 7:22am    
It was example. Modification can be made as per the requirement. Of course.
you can pass the values in variables which you want to replace and of which one

C#
            char a;
            char b;
            a = '2';
            b = '6';
            char c;
            char d;
            c = '5';
            d = '7';
Newstr= OldString.Replace(a, b).Replace(c, d);
 
Share this answer
 
If I were you, I would do that this way :

C#
string oldString = "A=3;B=2;C=5";


Separate each part :

C#
string[] parts = oldString.Split(";");
// You will then have
// parts[0] == "A=3"
// parts[1] == "B=2"
// parts[2] == "C=5"


Use a Dictionary<string, int> to store letters and values :

C#
var dic = new Dictionary<string, int>();
foreach (string part in parts) {
   string[] sep = part.Split("=");
   dic.Add(sep[0], int.Parse(sep[1]);
}


Replace the parts you need to as per your requirements

C#
dic["B"] = 6;
dic["C"] = 7;


Put everything back together

C#
string[] newParts = new string[parts.Length];
int i = 0;
foreach (var kvp in dic) {
   string val = string.Format("{0}={1}", kvp.Key, kvp.Value);
   newParts[i++] = val;
}
string newString = string.Join(newParts, ";");


That should get you near what you want.

Hope this helps. Regards.
 
Share this answer
 
v4
Hi All,

But
OldString
and newString created dynamically then what i can do ??
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900