Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most efficient way to format the following string?

I have a very simple question, and I shouldn't be hung up on this, but I am. Haha!

I have a string that I receive in the following format(s):

123

123456-D53

123455-4D

234234-4

123415

The desired output, post formatting, is:

123-455-444

123-455-55

123-455-5

or

123-455

The format is ultimately dependent upon the total number of characters in the original string..

I have several ideas of how to do this, but I keep thing there's a better way than string.Replace and concatenate...

Thanks for the suggestions..

Ian

like image 621
Ian P Avatar asked May 20 '10 17:05

Ian P


People also ask

What is %d in a string?

The %d operator is used as a placeholder to specify integer values, decimals, or numbers. It allows us to print numbers within strings or other values. The %d operator is put where the integer is to be specified. Floating-point numbers are converted automatically to decimal values.

What is string format () in Python?

Python String format() is a function used to replace, substitute, or convert the string with placeholders with valid values in the final string. It is a built-in function of the Python string class, which returns the formatted string as an output. The placeholders inside the string are defined in curly brackets.

How format () method is used for string formatting explain with examples?

Keyword parameters – This is a list of key=value parameters that can be accessed using the parameter's key inside curly braces. 4. The format() method returns a string that has been formatted. The format() function reads the type of arguments supplied to it and formats them according to the format codes in the string.

How do you use %s in Python?

The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value.


2 Answers

Tanascius is right but I cant comment or upvote due to my lack of rep but if you want additional info on the string.format Ive found this helpful. http://blog.stevex.net/string-formatting-in-csharp/

like image 197
Ryan Dunn Avatar answered Sep 28 '22 14:09

Ryan Dunn


I assume this does not merely rely upon the inputs always being numeric? If so, I'm thinking of something like this

private string ApplyCustomFormat(string input)
{
    StringBuilder builder = new StringBuilder(input.Replace("-", ""));

    int index = 3;
    while (index < builder.Length)
    {
        builder.Insert(index, "-");
        index += 4;
    }
    return builder.ToString();
}
like image 41
Anthony Pegram Avatar answered Sep 28 '22 14:09

Anthony Pegram