这两天遇到一个HR提了一个问题,要求将一个字符串实现反序操作,但是又不能将里面的数字反序,现在将用两种方法实现。
例如:
输入:ABC456
输出:456CBA
输入:123ABC
输出:CBA123
输入:ABC456XYZ789
输出:789ZYX456CBA
/// <summary>
/// 反转字符而不反转数字
/// by 佘中六
/// date 2022/01/01
/// </summary>
public class CalcHelper
{
public static string ReverseString(string s)
{
if (string.IsNullOrEmpty(s)) return null;
List<char> result = new List<char>();
Stack<char> stackAll = new Stack<char>();
Stack<char> stackNum = new Stack<char>();
int i;
//入栈反转所有字符
for (i = 0; i < s.Length; i++)
{
stackAll.Push(s[i]);
}
char temp;
//遍历全栈
for (i = 0; i < s.Length; i++)
{
temp = stackAll.Pop();
if (temp >= '0' && temp <= '9')
{
stackNum.Push(temp);//二次入栈将数字顺序变回来
}
else
{
while (stackNum.Count > 0)
{
result.Add((char)stackNum.Pop());
}
result.Add((char)temp);
}
}
while (stackNum.Count > 0)
{
result.Add((char)stackNum.Pop());
}
var array = result.ToArray();
return new string(array.ToArray());
}
public static string Reversal(string source)
{
int length = source.Length;
if (length <= 1) return source;
//获得字符串的字符数组形式
char[] charArray = source.ToCharArray();
//反转全部字符
List<char> array = new List<char>();
for (int i = 0; i < length; i++)
{
array.Insert(0, charArray[i]);
}
//二维数组
List<List<char>> chars = new List<List<char>>();
//二维数组的元素(一维数组)
List<char> item = new List<char>();
//遍历array
array.ForEach(word =>
{
if (item.Count == 0)
{
item.Add(word);
}
else
{
char lastWord = item.Last();
if (lastWord >= 48 && lastWord <= 57)
{
if (word >= 48 && word <= 57)
{
item.Add(word);
}
else
{
chars.Add(item);
item = null;
item = new List<char>();
item.Add(word);
}
}
else
{
if (word >= 48 && word <= 57)
{
chars.Add(item);
item = null;
item = new List<char>();
item.Add(word);
}
else
{
item.Add(word);
}
}
}
});
chars.Add(item);//添加最后一个数组
//二次反转数字
chars.ForEach(list =>
{
if (list[0] >= 48 && list[0] <= 57)
{
list.Reverse();
}
});
//合成一个数组
List<char> results = new List<char>();
chars.ForEach(list =>
{
list.ForEach(c =>
{
results.Add(c);
});
});
return new string(results.ToArray());
}
}