反转字符串

static string ReverseSentence(string sentence)
        {
            if (sentence == null)
                throw new ArgumentNullException("sentence");
            if (sentence.Length == 0)
                return sentence;

            char [] senten = new char[sentence.Length];
            for (int i = 0; i < senten.Length; i++) //将整个句子反转
            {
                senten[i] = sentence[senten.Length-1-i];
            }

            int start = 0;
            int length = 0;
            int index = 0;
            string rt = string.Empty;
            char[] word;
            while (index < senten.Length)
            {
                while (index <senten.Length)  //内循环
                {
                    if (senten[index] >= 65 && senten[index] <= 122) //若为字母,则不断对长度加一(单词是连续字母,故可以使用start+length的组合确定一个单词)
                    { 
                        length++;
                        index++;
                    }
                    else // 非字母
                    {
                        if (length == 0) //未发现连续字母
                        {
                            start++;  //调整单词开始位置start
                            rt += senten[index];
                            index++;
                        }
                        break;
                    }
                }
                if (length > 0)  //统计完一个单词,对其反转
                {
                    word = new char[length];
                    for (int i = start; i < start + length; i++)
                    {
                        word[i - start] = senten[i];
                    }
                    for (int i = 0; i < word.Length; i++)
                    {
                        rt += word[word.Length - i - 1];
                    }
                    start = start + length;
                    length = 0;
                }
            }
            return rt;

        }

你可能感兴趣的:(字符串)