'Array char operation C#
Anyone can help me how to optimize the code that i create or have better way to implement it? The rule is on the bottom
public string HandleLastNumber(char[] n_array)
{
var n_string = new StringBuilder();
if (n_array.All(x => char.IsDigit(x)))
{
return $"{new string(n_array)} -> {int.Parse(n_array) + 1}";
}
if (!n_array.Any(x => char.IsDigit(x)))
{
return $"{new string(n_array)}->{new string(n_array)}";
}
for (int i = n_array.Length - 1; i >= 0; i--)
{
if (!char.IsDigit(n_array[i]))
{
break;
}
n_string.Insert(0, n_array[i]);
}
var n_plus = int.Parse(n_string.ToString()) + 1;
var n_handled = n_plus.ToString()[^n_string.Length..];
var sub_clone = new string(n_array).Substring(0,n_array.Length-n_handled.Length);
return $"{new string(n_array)}->{sub_clone += n_handled}";
}
}
The rule is
Input char array, validate the last number, plus one at last number. then print old and new char array
result example:
- 00-> 01
- 99-> 00
- ABC123 -> ABC124
- ABCDGF -> ABCDGF
- AD33GVB99 -> AD33GVB00
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
