I wanna add s开发者_StackOverflowpace in string( string from array) after 2 characters, for example:
1234567890
should be 12 34 56 78 90
, any suggestions how to do that?
"0123567236359783590203582835"
.ToCharArray()
.Aggregate("",
(result, c) => result += ((!string.IsNullOrEmpty(result) && (result.Length+1) % 3 == 0)
? " " : "")
+ c.ToString()
);
// --> 01 23 56 72 36 35 97 83 59 02 03 58 28 35
You would probably have to do a loop as such:
int i = 0;
int amount = 2;
string s = "1234567890";
string withspaces = "";
while (i+amount < s.Length) {
s += s.Substring(i,i+amount);
s += " ";
i = i + amount;
}
This could be heavy on string usage, so make sure you read up on effective string concatenation
I would recommend following steps
Create a For loop which will go through the length of input string.
During each run of For loop concat ith elemen of string in to the result i.e.
result+=input[i];
Inside for loop keep track of count and after every
count%2 == 0
concat space to the result.result+=" ";
Hope this helps.
If your looking specifically to format a fixed amount of numbers, such as the example above, the following will fit your needs.
int n = 1234567890;
string s = String.Format("{0:00 00 00 00 00}", n);
Note, this assumes that your 1234567890
is stored as a number. It will not format if n
is of type string
. You can overcome this by casting n
to a number prior to formatting.
If you have an unbounded number of characters, you'll need a more versitile solution.
精彩评论