我的場景是我有一個多行文本框與多個值例如如下:asp.net翻轉字符串(交換字符)字符
firstvalue = secondvalue
anothervalue = thisvalue
我正在尋找一個快速簡便的場景,例如翻轉值如下:
secondvalue = firstvalue
thisvalue = anothervalue
你能幫忙嗎?
感謝
我的場景是我有一個多行文本框與多個值例如如下:asp.net翻轉字符串(交換字符)字符
firstvalue = secondvalue
anothervalue = thisvalue
我正在尋找一個快速簡便的場景,例如翻轉值如下:
secondvalue = firstvalue
thisvalue = anothervalue
你能幫忙嗎?
感謝
我猜測你的多行文本框會一直有文字這是你提到的格式 - 「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;
}
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>";
}
您也可以使用正則表達式組此。添加兩個多行文本框到頁面和一個按鈕。對於按鈕的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();
}
它給你一個很好的方式來處理左手和右手邊,你正在尋找交換,以替代與子和字符串長度工作。
這是要在瀏覽器或服務器上完成(使用JavaScript或VB?) – 2009-12-13 19:50:39