如何在C#中替换现有字符串中的值 [英] How to replace values in existing string in C#
问题描述
嗨朋友们,
我想替换现有字符串中的值c#
例如:OldString = A = 3; B = 2; C = 5,新值B = 6; C = 7;那么输出应该是A = 3; B = 6; C = 7;
请建议解决方案
请参阅
C#替换字符串示例 [ ^ ]
示例:string first = B = 2\" 跨度>;
string final = first.Replace( 2, 6);
问候..:)
你可以传递你想要替换的变量中的值以及哪一个
char a;
char b;
a = ' 2';
b = ' 6';
char c;
char d;
c = ' 5';
d = ' 7';
Newstr = OldString.Replace(a,b).Replace(c,d);
如果我是你,我会这样做方式:
string oldString = A = 3; B = 2; C = 5;
分开每个部分:
string [] parts = oldString.Split( ;);
// 您将
// parts [0] ==A = 3
// parts [1] ==B = 2
// parts [2] ==C = 5
使用Dictionary< string,int>
用于存储字母和值:
var dic = new 字典< string,int>();
foreach ( string part in 部分){
string [] sep = part.Split( =跨度>);
dic.Add(sep [ 0 ], int .Parse(sep [ 1 ]);
}
将您需要的部件更换为根据您的要求
dic [ B] = 6 ;
dic [ < span class =code-string> C] = 7 ;
将所有内容重新组合起来
string [ ] newParts = new string [parts.Length];
int i = 0 ;
foreach ( var kvp in dic){
stri ng val = string .Format( {0} = {1},kvp.Key,kvp.Value);
newParts [i ++] = val;
}
string newString = string .Join(newParts, ;);
这应该让你接近你想要的。
希望这会有所帮助。问候。
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
Refer this
C# Replace string examples[^]
Example:string first="B=2"; string final=first.Replace("2","6");
Regards..:)
you can pass the values in variables which you want to replace and of which one
char a; char b; a = '2'; b = '6'; char c; char d; c = '5'; d = '7'; Newstr= OldString.Replace(a, b).Replace(c, d);
If I were you, I would do that this way :
string oldString = "A=3;B=2;C=5";
Separate each part :
string[] parts = oldString.Split(";"); // You will then have // parts[0] == "A=3" // parts[1] == "B=2" // parts[2] == "C=5"
Use aDictionary<string, int>
to store letters and values :
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
dic["B"] = 6; dic["C"] = 7;
Put everything back together
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.
这篇关于如何在C#中替换现有字符串中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!