C# 反转句子

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ReverseSentence
{
class Program
{
static string ReverseSentence(string str)
{
if (str == null || str == string.Empty)
{
throw new Exception("input string is empty.");
}

if (str.Length <= 1)
{
return str;
}

string[] strArray = SplitWord(str);
string temp = "";
string result = "";
for (int i = 0; i < strArray.Length / 2; i++)
{
temp = strArray[i];
strArray[i] = strArray[strArray.Length - i - 1];
strArray[strArray.Length - i - 1] = temp;
}
foreach (string item in strArray)
{
result += item;
}
return result;
}

static string[] SplitWord(string str)
{
int count = 1;
for (int i = 0; i < str.Length; i++)
{
if (str[i] == ' ' || str[i] == ',' || str[i] == '.' || str[i] == '!')
{
count++;
count++;
}
}

string[] strArray = new string[count];
int j = 0;
for (int i = 0; i < str.Length; i++)
{
if (str[i] != ' ' && str[i] != ',' && str[i] != '.' && str[i] != '!')
{
strArray[j] += str[i];
}
else
{
j++;
strArray[j] += str[i];
j++;
}
}
return strArray;
}

static string ReverseSentence2(string sentence)
{
if (sentence == null || sentence == string.Empty)
{
throw new Exception("Input is null.");
}

if (sentence.Length <= 1)
{
return sentence;
}

char[] reverseString = new char[sentence.Length];
for (int i = 0; i < sentence.Length; i++)
{
reverseString[i] = sentence[sentence.Length - i - 1];
}

int index = 0;
int start = 0;
int length = 0;
string result = "";
while (index < reverseString.Length)
{
while (index < reverseString.Length)
{
if (reverseString[index] >= 65 && reverseString[index] <= 122)
{
index++;
length++;
}
else
{
if (length == 0)
{
result += reverseString[index];
start++;
index++;
}
break;
}
}

if (length > 0)
{
char[] word = new char[length];
for (int i = 0; i < length; i++)
{
word[i] = reverseString[start + length - i - 1];
}
for (int j = 0; j < length; j++)
{
result += word[j];
}
start += length;
length = 0;
}
}
return result;
}

static string ReverseSentence3(string str)
{
if (str == null || str.Length == 0)
{
throw new Exception("input can't be null");
}

string rStr = ReverseString(str, 0, str.Length - 1);

int start = 0;
int end = 0;
string result = "";

for (int i = 0; i < rStr.Length; i++)
{
if (rStr[i]== ' ' || rStr[i] == ',' || rStr[i] == '.' || rStr[i]== '!')
{
result += ReverseString(rStr, start, end -1);
result += rStr[i];
end++;
start = end;
}
else
{
end++;
}
}
result += ReverseString(rStr, start, end - 1);
return result;

}
static string ReverseString(string str, int start, int end)
{
string result = "";
for (int i = end; i >= start ; i--)
{
result += str[i];
}
return result;
}


static void Main(string[] args)
{
string str = Console.ReadLine();
string result = ReverseSentence2(str);
Console.WriteLine(result);
}
}
}
原文地址:https://www.cnblogs.com/Ligeance/p/2290297.html