我的方案是我有一个多行文本框,其中包含多个值,例如下面:
firstvalue = secondvalue
anothervalue = thisvalue
我正在寻找一个快速简便的方案来翻转价值,例如下面:
secondvalue = firstvalue
thisvalue = anothervalue
你能帮忙吗?
由于
答案 0 :(得分:1)
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>";
}
答案 1 :(得分:0)
我猜您的多行文本框将始终包含您提到的格式的文本 - “firstvalue = secondvalue”和“anothervalue = thisvalue”。并且考虑到文本本身不包含任何“=”。之后,它只是字符串操作。
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;
}
答案 2 :(得分:0)
您也可以使用正则表达式组。向页面添加两个多行文本框和一个按钮。对于按钮的onclick事件添加:
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();
}
它为您提供了一种处理您想要交换的左侧和右侧的好方法,作为处理子串和字符串长度的替代方法。