Reputation: 2369
I have a program that gets a string from a method. I want to know how to insert a string value to that string at certain positions.
For example:
mystring = "column1 in('a','b')column2 in('c','d')column3 in('e','f')";
Here, how would I insert the string value " and " after every occurance of the character ')' in mystring
?
PS. If possible, also include how not to insert it right at the end.
Upvotes: 3
Views: 12491
Reputation: 119856
If you mean, and I'm taking your string literally and as it comes:
mystring = "column1 in('a','b')column2 in('c','d')column3 in('e','f')"
Then you could just do:
mystring = mystring.Replace(")c", ") and c");
Which would result in:
mystring =
"column1 in('a','b') and column2 in('c','d') and column3 in('e','f')"
This is presuming you don't want a trailing "and".
Upvotes: 2
Reputation: 11162
System.Text.RegularExpressions.Regex.Replace(
mystring, "\\)(?=.+$)", ") and ");
The .+$
portion of the regular expression ensures that the closing parenthesis is not at the end of the line. If you are going to be doing this often, I'd recommend creating and persisting a Regex
object for the pattern.
// Do this once somewhere:
System.Text.RegularExpressions.Regex insertAndPattern =
new System.Text.RegularExpressions.Regex("\\)(?=.+$)");
// And later:
insertAndPattern.Replace(mystring, ") and ");
EDIT: Just realized I'm an idiot. Fixed the patterns above from "\\).+$"
to "\\)(?=.+$)"
, so that the .+$
part is not included (and thereby replaced) in the match.
Upvotes: 0
Reputation: 82375
You could accomplish this with replace..
string mystring = "column1 in('a','b')column2 in('c','d')column3 in('e','f')";
mystring = mystring.Replace(")", ") and ").TrimEnd(" and".ToCharArray());
Resulting In:
"column1 in('a','b') and column2 in('c','d') and column3 in('e','f')"
Upvotes: 2
Reputation: 19378
Probably the simplest:
mystring = mystring.Replace(")", ") and ");
mystring = mystring.Substring(0, mystring.Length - " and ".Length);
Upvotes: 5
Reputation: 56984
Strings are immutable, so you cannot 'just' change the value of that string. Each modification that you want to make to a string, leads to a new instance of a string.
This is maybe how you could achieve what you want:
string s = " x in (a, b) y in (c, d) z in (e , f)";
string[] parts = s.Split (')');
StringBuilder result = new StringBuilder ();
foreach( string part in parts )
{
result.Append (part + ") and ");
}
Console.WriteLine (result.ToString ());
But maybe there are better solutions ...
Anyway, how come you receive that string (which looks like a part of a where clause of a sql statement) in that way ?
Upvotes: 2