1.问题:
给定一个字符串,将其中的单词倒叙输出
例如:输入
"the sky is blue
"
输出:
"blue is sky the
"
2.思路:
思路:
将字符串中所有的单词都提取出来,然后倒叙输出即可。
3.C#实现
实现1,自己实现单词提取:
public static string ReverseWords1(string s)
{
string res = "";
List<string> words = new();
bool flag = false;
s += ' ';
for (int i = 0; i < s.Length; i++)
{
if (!s[i].Equals(' '))
{
flag = false;
res += s[i];
}
else
{
if (!flag)
{
flag = true;
if (!res.Equals(""))
{
words.Add(res);
res = "";
}
}
}
}
if (words.Count==1)
{
return words[0];
}
else
{
res = words[words.Count-1];
for (int j = words.Count - 2; j > 0; j--)
{
res = res + " " + words[j];
}
res = res + " " + words[0];
}
return res;
}
实现2,采用C#提供的split函数
public static string ReverseWords2(string s)
{
string res = "";
string[] characters= s.Split(' ',StringSplitOptions.RemoveEmptyEntries);
int lenth = characters.Length;
if (lenth == 1)
{
return characters[0];
}
res = characters[lenth - 1];
for (int i = lenth - 2; i >0; i--)
{
res = res + ' '+ characters[i];
}
res = res+' '+ characters[0];
return res;
}