7

我是一个真正的新手,虽然我发现了一个非常相似的问题和答案(Winforms C# 更改字符串文本顺序),但我仍然需要一些帮助,尤其是由于下面的第 3 点,这使得它有点棘手。

  1. 该字符串由 3 个“单词”组成,需要更改其顺序。字符串始终具有相同的模式:“WordOne WordTwo WordThree”——例如“Car Storage Sydney”、“Boat Storage Melbourne”和“Caravan Storage Brisbane”。

  2. 每个“单词”总是由一个空格分隔。据我了解,这将用于拆分变量,然后可以重新格式化以实现所需的顺序更改(参见下面的 4)

  3. 这就是它变得有点棘手的地方:第三个“单词”有时实际上是两个单词,即“单词三”而不是“单词三”,也许用另一个例子更好地解释:“黄金海岸船存储”

  4. 所需的顺序更改是“WordThree WordOne WordTwo”(基本上,只是将“WordThree”从后面移到前面)所以使用与上面 1 中相同的示例,最终结果将是“Sydney Car Storage”、“Melbourne Boat Storage” ”和“布里斯班大篷车仓库”。而棘手的一个,基于有时两个词的“三字”,如上图 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”何时包含两个单词并以某种方式将它们作为一个单词处理。我想你知道我的意思!

急切地等待一些帮助!

4

5 回答 5

6

你可以告诉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);
于 2013-03-05T17:03:40.420 回答
3
string wordsBefore = "WordOne WordTwo WordThree";
string[] wordsWorking = wordsBefore.Split();
string wordsAfter = ("{0} {1} {2}", string.Join(" ", wordsWorking.Skip(2)), wordsWorking[0], wordsWorking[1]);
于 2013-03-05T16:58:59.840 回答
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);
于 2013-03-05T17:03:37.060 回答
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]);
于 2013-03-05T17:03:13.753 回答
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]);

希望能帮助到你!

于 2013-03-05T17:09:43.297 回答