样本string
A3148579
预期结果:
798514A3
我试过这个代码:
public static string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}实际结果为9758413A
但我要798514A3

谢谢大家
发布于 2020-07-26 17:01:29
您可以将初始字符串拆分为size = 2块(例如,在Substring的帮助下);注意,ToCharArray()返回chars,即size = 1块。
让我们概括一下解决方案:现在我们有了块的size
代码:
using System.Linq;
...
public static string Reverse(string s, int size = 2) {
if (size < 1)
throw new ArgumentOutOfRangeException(nameof(size));
if (string.IsNullOrEmpty(s))
return s;
int n = s.Length / size + (s.Length % size == 0 ? 0 : 1);
return string.Concat(Enumerable
.Range(0, n)
.Select(i => i < n - 1 ? s.Substring(i * size, size) : s.Substring(i * size))
.Reverse());
}演示:
Console.Write(Reverse("A3148579"));结果:
798514A3发布于 2020-07-26 16:07:09
You can try below code. This is just to give you a idea and you can update based on the test cases and requirement. Below code works fine for your input which you have mentioned. I have not considered if the length is odd. You can do your research and update logic which will help you to learn and know more.
string input = "A3148579";
Stack stack = new Stack();
int count = 0;
string output = "";
for (int i = 0; i < input.Length/2; i++)
{
stack.Push(input.Substring(count, 2));
count = count + 2;
}
while (stack.Count > 0)
{
output += stack.Pop().ToString();
}发布于 2020-07-26 15:48:12
使用Lambda表达式扩展Array类以包含一个名为Split的新方法:
public static class MyArrayExtensions
{
/// <summary>
/// Splits an array into several smaller arrays.
/// </summary>
/// <typeparam name="T">The type of the array.</typeparam>
/// <param name="array">The array to split.</param>
/// <param name="size">The size of the smaller arrays.</param>
/// <returns>An array containing smaller arrays.</returns>
public static IEnumerable<IEnumerable<T>> Split<T>(this T[] array, int size)
{
for (var i = 0; i < (float)array.Length / size; i++)
{
yield return array.Skip(i * size).Take(size);
}
}
}测试新的数组类方法:
[TestMethod]
public void TestSplit2()
{
string str = "A3148579";
char[] array1 = new char[str.Length];
for (int i = 0; i < array1.Length; i++)
{
array1[i] = i;
}
// Split into smaller arrays of maximal 2 elements
IEnumerable<IEnumerable<int>> splited = array1.Split<int>(2);
int j = 0;
foreach (IEnumerable<int> s in splited){
j++;
}
log.InfoFormat("Splitted in to {0} smaller arrays.", j);
}最后,您只需要反转得到的数组(更小)。
https://stackoverflow.com/questions/63102027
复制相似问题