My scenario is i have a multiline textbox with multiple valu开发者_开发百科es e.g. below:
firstvalue = secondvalue
anothervalue = thisvalue
i am looking for a quick and easy scenario to flip the value e.g. below:
secondvalue = firstvalue
thisvalue = anothervalue
Can you help ?
Thanks
protected void btnSubmit_Click(object sender, EventArgs e)
{
string[] content = txtContent.Text.Split('\n');
string ret = "";
foreach (string s in content)
{
string[] parts = s.Split('=');
if (parts.Count() == 2)
{
ret = ret + string.Format("{0} = {1}\n", parts[1].Trim(), parts[0].Trim());
}
}
lblContentTransformed.Text = "<pre>" + ret + "</pre>";
}
I am guessing that your multiline text box will always have text which is in the format you mentioned - "firstvalue = secondvalue" and "anothervalue = thisvalue". And considering that the text itself doesn't contain any "=". After that it is just string manipulation.
string multiline_text = textBox1.Text;
string[] split = multiline_text.Split(new char[] { '\n' });
foreach (string a in split)
{
int equal = a.IndexOf("=");
//result1 will now hold the first value of your string
string result1 = a.Substring(0, equal);
int result2_start = equal + 1;
int result2_end = a.Length - equal -1 ;
//result1 will now hold the second value of your string
string result2 = a.Substring(result2_start, result2_end);
//Concatenate both to get the reversed string
string result = result2 + " = " + result1;
}
You could also use Regex groups for this. Add two multi line textboxes to the page and a button. For the button's onclick event add:
using System.Text.RegularExpressions;
...
protected void Button1_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
Regex regexObj = new Regex(@"(?<left>\w+)(\W+)(?<right>\w+)");
Match matchResults = regexObj.Match(this.TextBox1.Text);
while (matchResults.Success)
{
string left = matchResults.Groups["left"].Value;
string right = matchResults.Groups["right"].Value;
sb.AppendFormat("{0} = {1}{2}", right, left, Environment.NewLine);
matchResults = matchResults.NextMatch();
}
this.TextBox2.Text = sb.ToString();
}
It gives you a nice way to deal with the left and right hand sides that you are looking to swap, as an alternative to working with substrings and string lengths.
精彩评论