2009-12-13 34 views
0

我的场景是我有一个多行文本框与多个值例如如下:asp.net翻转字符串(交换字符)字符

firstvalue = secondvalue

anothervalue = thisvalue

我正在寻找一个快速简便的场景,例如翻转值如下:

secondvalue = firstvalue

thisvalue = anothervalue

你能帮忙吗?

感谢

+0

这是要在浏览器或服务器上完成(使用JavaScript或VB?) – 2009-12-13 19:50:39

回答

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; 

} 
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>"; 

} 
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(); 
} 

它给你一个很好的方式来处理左手和右手边,你正在寻找交换,以替代与子和字符串长度工作。