码迷,mamicode.com
首页 > Windows程序 > 详细

(C#) 反转字符串,反转一个句子中单词。

时间:2015-11-14 13:47:34      阅读:398      评论:0      收藏:0      [点我收藏+]

标签:

这个是非常基本的一道面试题,但是要考虑周全。

首先反转一个字符串:

基本思路是变成Char数组,然后调用C#里面的方法,或者设定两个index,从头,尾向中间遍历,并交换。

方法一: Array.Reverse(char *). 注意在开始的时候要判断字符串为null或空。

        public static string ReverseString(string input)
        {
            if (String.IsNullOrEmpty(input))
            {
                return input; 
            }

            char[] charArray = input.ToCharArray();
            Array.Reverse(charArray);
            return new String(charArray); 
        }

方法二: 交换字符。

        public static string ReverseString1(string input)
        {
            if(String.IsNullOrEmpty(input))
            {
                return input; 
            }

            char[] charArray = input.ToCharArray();
            char tmp;  
            for(int i = 0, j = charArray.Length - 1; i < j;  i++, j--)
            {
                tmp = charArray[i];
                charArray[i] = charArray[j];
                charArray[j] = tmp; 
            }

            return new string(charArray); 
        }

 

反转句子当中的单词:

        public static string ReverseWords(string input)
        {
            if (String.IsNullOrEmpty(input))
            {
                return input; 
            }

            string[] splits = input.Split( ).Select(str=> str.Trim()).ToArray();
            StringBuilder output = new StringBuilder(); 
            for(int i = splits.Length - 1; i >= 0 ; i--)
            {
                output.Append(splits[i]); 
                if(i != 0)
                {
                    output.Append(" "); 
                }
            }

            return output.ToString(); 
        }

 

(C#) 反转字符串,反转一个句子中单词。

标签:

原文地址:http://www.cnblogs.com/fdyang/p/4964106.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!