如何在C#中更改字符串元素位置

如何更改字符串元素位置。

例:

... 
....

 ... 
...

要么。

 ... 
....

 ... 
...

所以我需要在C#中将class="" id=""改为id="" class="" 。 怎么样?

问题没有明确定义,但如果目标是简单地在div标签中交换’id’和’class’属性,那么这样的东西就可以工作:

 public class SSwap { string str1 = @"
"; string str2 = @"
"; public SSwap() { Console.WriteLine("Before : " + str1 + "\nAfter : " + swap_string(str1)); Console.WriteLine("Before : " + str2 + "\nAfter : " + swap_string(str2)); } public string swap_string(string str) { string retStr = "
props = new Dictionary(); Match m = theRegex.Match(str); int classPos=-1, idPos=-1, pos = 0; while (m.Success) { if (m.Result("$1") == "class") classPos = pos; // Remember where class was if (m.Result("$1") == "id") idPos = pos; // Remember where id was props[m.Result("$1")] = m.Result("$2"); m = m.NextMatch(); pos++; } pos = 0; foreach (string s in props.Keys) { if (pos == classPos) // put id where class was { retStr += @"id=" + props["id"] + @" "; } else if (pos == idPos) // put class where id was { retStr += @"class=" + props["class"] + @" "; } else // put everything else where ever it appears in the dictionary { retStr += s + @"=" + props[s] + @" "; } pos++; } retStr += ">"; return retStr; } }

当然这没有错误检查,对没有严格格式化的字符串反应不好,就像你给出的两个例子,不能容忍混合情况等等。一些聪明的正则表达式操作可能在几行中完成它但是不清楚你所寻求的那种复杂,难以理解,难以维持的正则表达式。

  public string swap_string(string str) { Regex classRegex = new Regex(@"class=""(.+?)"""); Regex idRegex = new Regex(@"id=""(.+?)"""); string classVal = classRegex.Match(str).Value; string idVal = idRegex.Match(str).Value; str = classRegex.Replace(str, "__TMPSTRING__"); str = idRegex.Replace(str, classVal); str = str.Replace("__TMPSTRING__", idVal); return str; } 

如果开始和结束标记不是静态字符串,您也可以就地替换“class”和“id”属性。 我得到的印象是,有更多的细节,然后你告诉我们,所以很难弄清楚你真正需要什么。

我不能为我的生活想象为什么需要这样做,但你可以用一点点XSLT来做到这一点: