如何在c#中替换字符串中的子字符串 [英] How to replace substring in a string in c#
问题描述
我想用字符串替换子串134和1254
((startTime == 134)&&&(endTime == 1254))<具有一些动态值的
- 例如分别为154和1234。我已经使用String.Split方法编写了代码,但似乎代码很长。如何让它更短更强大?
在我的要求中它是从xml文件中获取((startTime == 134)&&(endTime == 1254))其中startTime的值和endTimekeeps一起根据以下代码的操作进行更改
以下是代码:
I want to replace the substrings 134 and 1254 in a string
((startTime==134)&&(endTime==1254))
with some dynamic value - say, for example, 154 and 1234 respectively. I have written the code to place using String.Split method but it seems the code is very long. How can I make it shorter and more robust?
In my requirement it is fetching ((startTime==134)&&(endTime==1254)) from xml file where the value of startTime and endTimekeeps on changing based on manipulation from below code
Here is the code:
string s = "((startTime==134)&&(endTime==1254))";
string[] time = s.Split(')').Reverse().ToArray();
var start = time.FirstOrDefault(s => s.Contains("startTime")).Split('=')[2];
var end = time.FirstOrDefault(e => e.Contains("endTime")).Split('=')[2];
start ="154";
end = "1234"
time[3] = "((startTime=="+start;
time[2] = "&&(endTime=="+end;
string joinedstring;
joinedstring= String.Join(")", time.Reverse());
推荐答案
您好,
请尝试以下代码:
Hi,
Pleae try the following code:
string joinedstring;
string split = "&&";
string time1 = "154";
string time2 = "1234";
string s = "((startTime==134)&&(endTime==1254))";
string[] lines = Regex.Split(s, split);
Console.WriteLine(s);
Console.WriteLine(Regex.Replace(lines[0], @"\d+", time1) + split + Regex.Replace(lines[1], @"\d+", time2));
Console.ReadKey();
我尝试使用RegEx。它对我有用。
希望这有帮助!! :) :)
如果需要其他任何东西,还原。
I tried that using RegEx. It worked for me.
Hope this helps !! :) :)
Revert in case anything else is required.
如果我理解你的问题,只需使用 String.Replace方法(字符串,字符串) [ ^ ]
If I understood your question correctly, just use String.Replace Method (String, String)[^]
有些时候我遇到了一些字符串替换问题。
假设,我有字符串1234gg1234567,我想从起始位置替换1234或仅从结尾取代。
我该怎么办?
试试这段代码。根据您的需要进行修改。这是基于字符串中字符的索引。
Hi,
some time i faced some problem for replace in a string.
lets assume, i have string "1234gg1234567" and i want to replace "1234" from starting position only OR only from end.
how will i do?
try this code. modify according to you need. This is based on index of a character in a string.
string str = "((startTime==134)&&(endTime==1254))";
int pos_start_1 = str.IndexOf("==") + 2;
int pos_end_1 = str.IndexOf(")&&(");
int pos_start_2 = str.LastIndexOf("==") + 2;
int pos_end_2 = str.IndexOf("))");
string time1 = str.Substring(pos_start_1, (pos_end_1 - pos_start_1));
string time2 = str.Substring(pos_start_2, (pos_end_2 - pos_start_2));
string time1_new = "time1_new";
string time2_new = "time1_new";
string newString = str.Replace(time1, time1_new).Replace(time2, time2_new);
这篇关于如何在c#中替换字符串中的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!