15

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?

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());
1
  • 3
    Fahim's answer is basically perfect solution to question as asked. You may want to clarify what your actual task is as String.Format (like ((startTime=={0})&&(endTime=={1}))) or proper parsing of exception may be better approach to your actual problem (consider if new question is more appropriate if more complete requirements change it too much). Commented Mar 2, 2015 at 3:49

2 Answers 2

25

Replace chars in a string using replace method as shown here

string output = input.Replace("old_value", "new_value");
Sign up to request clarification or add additional context in comments.

Comments

0

This is the shortest you can do without Regex.

    string str = "((startTime==134)&&(endTime==1254))";
    string[] timeArr = str.Replace("(","").Replace(")","").Split(new string[] { "&&" }, StringSplitOptions.None);
    string[] startArr = timeArr[0].Split(new string[] { "=="}, StringSplitOptions.None);
    string[] endArr = timeArr[1].Split(new string[] { "=="}, StringSplitOptions.None);
    startArr[1] = "154";
    endArr[1] = "1234";
    string newStr = "(("+string.Join("==",startArr)+string.Join("==",endArr)+"))";

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.