Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting string to 10 characters

I am currently working on a project where I need to format a string to be only 10 characters long. But has to start in a certain way and finish with an incrementing counter.

E.G the number will be in the format of:

0100000001
0100000002
0100000003
...
0100000010
0100000011

I.e. the first two numbers will stay the same only the last digits will keep incrementing but the string has to remain 10 characters long.

How could I do this I have tried using String.Format but doesn't appear to work.

UPDATE I've tried using the following

destination = String.Format("07000000{0}", messageCount);

This kind of works but once the messageCount gets above 10 the length becomes 11 and it needs to stay no longer than 10

like image 287
Boardy Avatar asked Jan 23 '12 14:01

Boardy


People also ask

What is %s and %D in Java?

%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"

What is %s in string format?

%s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string.

What is str format () in Python?

Python's str. format() method of the string class allows you to do variable substitutions and value formatting. This lets you concatenate elements together within a string through positional formatting.

How do you write in string format?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Parameter: The locale value to be applied on the format() method.


3 Answers

D8 means format as a decimal with up to 8 leading zeroes

string.Format("01{0}", counter.ToString("D8"));
like image 172
soniiic Avatar answered Nov 03 '22 01:11

soniiic


try

String.Format("01{0:00000000}", i);
like image 33
D Stanley Avatar answered Nov 03 '22 00:11

D Stanley


You can use this:

var counter = 11;
var fixedPart = "01";
var result = fixedPart + counter.ToString().PadLeft(8,'0');
like image 32
Daniel Hilgarth Avatar answered Nov 03 '22 01:11

Daniel Hilgarth