I need to add "开发者_如何学Go123" and zeros for any string - but the resulting string must be exactly 12 characters long.
For example:
28431 = 123000028431
987 = 123000000987
2 = 123000000002
How to do this in C#?
Well, you could use:
string result = "123" + text.PadLeft(9, '0');
In other words, split the task in half - one part generating the "000028431", "000000987" etc part using string.PadLeft
, and the other prefixing the result with "123" using simple string concatenation.
There are no doubt more efficient approaches, but this is what I'd do unless I had a good reason to believe that efficiency was really important for this task.
var result = string.Format("123{0}", number.PadLeft(9, '0'));
You could try:
var str = String.Format("123{0:0#########}", 28431);
or
var str = String.Format("123{0:000000000}", 28431);
Well, if you have numbers less than 1000000000, you could just add 123000000000 to each number.
Assuming...
- The strings are known to always contain representations of decimal integers.
- The represented integer is always less than 109.
...you could do this:
(123000000000 + long.Parse(s)).ToString()
try this code
string argString ="28431 ";
StringBuilder sb =new StringBuilder();
sb.Append(argString);
for (int i = 12 -argString.Length-3; i >0 ; i--)
{
sb.Insert(0, "0");
}
string result = string.Format("123{0}",sb.ToString());
精彩评论