我是一个真正的新手,虽然我发现一个问题和答案非常相似(Winforms C# change string text order)我仍然需要一些帮助,特别是由于下面的第3点使得它有点棘手。 / p>
该字符串由3个“单词”组成,其顺序需要更改。字符串总是具有相同的模式:“WordOne WordTwo WordThree” - 一些例子是“Car Storage Sydney”,“Boat Storage Melbourne”和“Caravan Storage Brisbane”。
每个'Word'总是由一个空格分隔。据我了解,这将用于拆分变量,然后可以重新格式化以实现所需的订单更改(见下文4)
这是一个有点棘手的地方:第三个'Word'有时实际上是两个单词,即“Word 3”而不是“WordThree”或许更好地用另一个例子解释:“Boat Storage Gold Coast”< / p>
所需的订单更改是“WordThree WordOne WordTwo”(基本上,只是将“WordThree”从后面移到前面)所以使用与上面1中相同的示例,完成的结果将是“悉尼汽车存储” “,”墨尔本船存储“和”布里斯班大篷车存储“。基于有时两个措辞的“三个字”,如上面的3.所示,那个棘手的问题将是“黄金海岸船存储”
我希望我已经解释得很好。
除了上面3.中描述的问题,我认为它应该是这样的,只是我粗略的新手尝试代码:
string wordsBefore = "WordOne WordTwo WordThree";
string[] wordsWorking = wordsBefore.Split(new string[]{" "});
string wordsAfter = ("{0} {1} {2}", wordsWorking[2], wordsWorking[0], wordsWorking[1]);
我认为这非常接近?
但是,当然,由于上面3中描述的问题,需要额外的代码来检测“WordThree”何时包含两个单词并以某种方式将它们作为一个单词处理。我想你知道我的意思了!
急切等待一些帮助!
答案 0 :(得分:5)
您可以告诉Split
仅提供一定数量的结果:
string wordsBefore = "WordOne WordTwo Word Three";
string[] wordsWorking = wordsBefore.Split(new [] {' '}, 3);
string wordsAfter = string.Format("{0} {1} {2}",
wordsWorking[2], wordsWorking[0], wordsWorking[1]);
// result: "Word Three WordOne WordTwo"
或者如果你想聪明地使用String.Format
:
string wordsBefore = "WordOne WordTwo Word Three";
string[] wordsWorking = wordsBefore.Split(new [] {' '}, 3);
string wordsAfter = string.Format("{2} {0} {1}", wordsWorking);
答案 1 :(得分:3)
string wordsBefore = "WordOne WordTwo WordThree";
string[] wordsWorking = wordsBefore.Split();
string wordsAfter = ("{0} {1} {2}", string.Join(" ", wordsWorking.Skip(2)), wordsWorking[0], wordsWorking[1]);
答案 2 :(得分:2)
保持简单。
string wordsBefore = "WordOne WordTwo WordThree";
string[] wordsWorking = wordsBefore.Split(new string[]{" "});
string word1 = wordsWorking[0];
string word2 = wordsWorking[1];
string word3 = wordsWorking[2];
if (wordsWorking.length == 4)
word3 = word3 + " " + wordsWorking[3];
string wordsAfter = ("{0} {1} {2}", word3 word1, word2);
答案 3 :(得分:0)
const string wordsBefore = "WordOne WordTwo Word Three";
string[] wordsWorking = wordsBefore.Split();
var thirdWord = wordsWorking.Skip(2).Aggregate((s, s1) => s + " " + s1);
string wordsAfter = string.Format("{0} {1} {2}", thirdWord, wordsWorking[0], wordsWorking[1]);
答案 4 :(得分:0)
以下是我的例子:
string text = "word one<splittag>word two and some other words<splittag>word three with some text";
string[] words = text.Split(new string[] { "<splittag>" }, StringSplitOptions.None);
Label1.Text = String.Format("{2},{0},{1}", words[2], words[0], words[1]);
希望它有所帮助!