class Program
{
static void Main(string[] args)
{
string input = "白日依山尽,黄河入海流。欲穷千里目,更上一层楼。";
IStringInverter inverter1 = new StringInverter1();
string str1 = inverter1.PiecewiseInvert(input);
Console.WriteLine(str1);
IStringInverter inverter2 = new StringInverter2();
string str2 = inverter2.PiecewiseInvert(input);
Console.WriteLine(str2);
Console.Read();
}
}
/// <summary>
/// 根据标点符号反转
/// </summary>
class StringInverter1 : IStringInverter
{
#region IStringInverter 成员
public string PiecewiseInvert(string input)
{
StringBuilder sb = new StringBuilder();
int spindex = input.IndexOf('。');
for (int i = 0; i < input.Length; i++)
{
if (spindex > -1)
{
if (input[i] != '。')
{
sb.Append(input[spindex - i - 1]);
}
else
{
i -= (spindex + 1);
input = input.Remove(0, spindex + 1);
spindex = input.IndexOf('。');
sb.Append('。');
}
}
else
{
sb.Append(input[input.Length - i - 1]);
}//每句反转
}
string[] two = sb.ToString().Split('。', ',');
if (two.Length > 3)
return two[1] + "," + two[0] + "。" + two[3] + "," + two[2] + "。";
else
throw new ArgumentException("此方法只能处理**,**。的语句");
}
#endregion
}
/// <summary>
/// 利用正则,3种方法反转字符串
/// </summary>
class StringInverter2 : IStringInverter
{
#region IStringInverter 成员
public string PiecewiseInvert(string input)
{
Regex punctuationReg = new Regex(@"[,。]");
MatchCollection matchs = punctuationReg.Matches(input);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < matchs.Count; i++)//匹配出有多少段
{
int index = input.IndexOf(matchs[i].Value);
string section = input.Remove(index);
input = input.Remove(0, index + 1);
#region 遍历一半,利用临时变量
var tempchars = section.ToCharArray();
int templen = tempchars.Length;
for (int c = 0; c < templen / 2; c++)
{
char temp = tempchars[c];
tempchars[c] = tempchars[templen - c - 1];
tempchars[templen - c - 1] = temp;
}
section = string.Join("", tempchars);
sb.Append(section);
#endregion
#region 遍历一遍
//for (int c = 0; c < section.Length; c++)
//{
// sb.Append(section[section.Length - c - 1]);//反转每句
//}
#endregion
#region array的静态方法反转
//var chars = section.ToCharArray();
//Array.Reverse(chars);
//section = string.Join("", chars);
//sb.Append(section);
#endregion
sb.Append(matchs[i].Value);//加上标点
}
return sb.ToString();
}
#endregion
}
interface IStringInverter
{
string PiecewiseInvert(string input);
}