算法 字符串 --- 实现字符串单词的反转

这个算法题是要求实现单词反转功能

比如   “This is a word” 反转后结果: “word a is This”

这个题目,我们需要使用数组Array的Reverse功能, 先把字符串按照空格" "间隔(要考虑单词间有多个空格的情况)转换为单词数组,然后使用Array.Reverse()方法进行反转,再把反转后的数组用” “连接成新的字符串

代码如下

public class Solution
{
    public string ReverseWords(string str)
    {
        var words = str.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
        Array.Reverse(words);
        return string.Join(" ", words);
    }
}

 

posted on 2026-09-27 15:41  新西兰程序员  阅读(1)  评论(0)    收藏  举报