如何在字符串中的单词a之间交换和重新定殖

时间:2018-12-20 21:05:43

标签: c#-2.0

一个H.W C#问题: 我有一个包含4个单词的字符串(例如:string = "Joe walking every day"; 任务是识别第三个单词(任何字符串...),并与第一个单词交换 所以我的输出字符串将是“每天乔走天”

我当时想用于?如果?索引器?一个方向将与完整答案一样好

注释中的代码

int counter = 0;
string lyrics = "Joe walking every day";
Console.WriteLine(lyrics[3]);
for (int i = 0; i < lyrics.Length; i++) {
    if (lyrics[i] ==' ') {
        if (counter==2) {
            //must be the start of 3rd word
            if (counter==3) {
                //must be the end of 3rd word
            }
        }
    }
} //this is as far I reached

1 个答案:

答案 0 :(得分:0)

您可以尝试:

string lyrics = "Joe walking every day";
String[] words = lyrics.Split(" ");
string firstWord = words[0];
string thirdWord = words[2];
words[0] = thirdWord;
words[2] = firstWord;
string swapped = string.Join(" ",words);
Console.WriteLine(swapped);