给定一个字符串一个数字,格式化为每个区块3位数字



我需要创建一个接收一串数字的方法,例如1747095800987474434。然后,它需要格式化为三个块,并在数组中返回,例如{174709580098747434}。

这是我迄今为止所拥有的。我认为这做得不对。此外,如果我有一个非常大的数字,上面也没有用。

我对C#很陌生,只是个初学者!

using System;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
string ques = "17470958834";
Console.WriteLine(Chunk(ques));
}
public static string Chunk(string num)
{
// long inInt = Convert.ToInt64(num);
string ans = "";
for (int i = 0; i < num.Length; i += 3)
{
if (i == 2)
{
ans.Insert(2, "-");
}
else if (i == 5)
{
ans.Insert(5, "-");
}
else if (i == 8)
{
ans.Insert(8, "-");
}
else if (i == 11)
{
ans.Insert(11, "-");
}
}
return ans;
}
}
}

如果您NuGet;系统"交互式";扩展以获得Buffer运算符,然后您可以这样做:

var number = "174709580098747434";
var output =
String.Join(
" ",
number //174709580098747434 - string
.Reverse() //434747890085907471 - char array
.Buffer(3) //434 747 890 085 907 471 - array of char array
.Select(x => String.Concat(x.Reverse())) //434 747 098 580 709 174 - string array
.Reverse()); //174 709 580 098 747 434 - string

这给了我174 709 580 098 747 434

如果没有Buffer,你可以使用稍微难看一点的版本:

var output =
String.Join(
" ",
number
.Reverse()
.Select((x, n) => (x, n))
.GroupBy(z => z.n / 3)
.Select(z => z.Select(y => y.x))
.Select(x => String.Concat(x.Reverse()))
.Reverse());

对于初学者来说,它应该更简单,并且应该发人深省。遵循以下技术:

string value = "174709580098747434";
int chunk = 3;
int length = value.Length;
for (int i = 0; i < length; i += chunk)
{
if (i + chunk > length) chunk = length - i;
Console.WriteLine(value.Substring(i, chunk));
}
Console.ReadLine();

我希望下面的代码能解决您的问题。

public static  string[] Chunk(string number)
{
int count = (number.Length / 3)+(number.Length % 3 > 0 ? 1 : 0);
string[] result = new string[count];
for (int i = 0; i < count; i++)
{
result[i] = number.Substring(i*3, ((i+1) * 3) < number.Length ? 3 : number.Length - (i * 3));
}
return result;
}

如果你愿意,你甚至可以把它概括如下:

///number is string value
///splitStringCount is count which you want your string to get splitted.
private string[] Chunk(string number, int splitStringCount = 3)
{
int count = (number.Length / splitStringCount) +(number.Length % splitStringCount > 0 ? 1 : 0);
string[] result = new string[count];
for (int i = 0; i < count; i++)
{
result[i] = number.Substring(i* splitStringCount, ((i+1) * splitStringCount) < number.Length ? splitStringCount : number.Length - (i * splitStringCount));
}
return result;
}

如果您只想在返回数组中输入3位数字,请检查以下代码:

如下调用此方法:

Chunk("174709580098747434");

方法逻辑如下:

public static string[] Chunk(string number, int splitStringCount = 3)
{
int count = (number.Length / splitStringCount);
string[] result = new string[count];
for (int i = 0; i < count; i++)
{
result[i] = number.Substring(i* splitStringCount, splitStringCount);
}
return result;
}