HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Trim leading zeroes from second component of a string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
leadingtrimsecondzeroescomponentfromstring

Problem

I have a collection of strings as follows:


44.01

44.02

44.03

44.04

44.12

46.05

46

... and so on.

I want to remove leading zeros from the component of the string after the full stop.

As you can see from above, not all strings have a sub-component and not all sub-components will have leading zeros.

Is there a more elegant way of doing that from my attempt?

List codesWithSubCodes = new List
    {
        "44.01", "44.02", "44.03", "44.04", "44.05", "44.06", "44.07", "44.08"
    };

    var codes = new List();
    foreach (var code in codesWithSubCodes)
    {
        if (code.Contains('.'))
        {
            var prefix = code.Split('.')[0];
            var subCode = code.Split('.')[1].TrimStart('0');
            codes.Add(prefix + '.' + subCode);
        }
        else
        {
            codes.Add(code);
        }
    }

    foreach (var code in codes)
    {
        Debug.WriteLine(code);
    }

Solution

The biggest thing I can see, which may or may not be an issue, is the manner in which you process the strings.

if (code.Contains('.'))
    {
        var prefix = code.Split('.')[0];
        var subCode = code.Split('.')[1].TrimStart('0');
        codes.Add(prefix + '.' + subCode);
    }
    else
    {
        codes.Add(code);
    }


This could be rewritten as:

var codeSections = code.Split('.');
var code = codeSections[0];

if (codeSections.Length == 2)
    code += "." + codeSections[1].TrimStart('0');

codes.Add(code);


This saves you LoC, and probably makes it faster. (You could also possible make this a StringBuilder as well.) And in my opinion, this is more readable/concise/descriptive.

Another alternative:

code = code.Replace(".0", ".");


Both should have the same effect on the cases you provided.

However, if, for whatever reason, one of the cases ends up as 46.00, then the second method will only make it 46.0. Choose that method with great caution.

As the OP pointed out in an edit that should have been a comment, this code can all be done as LINQ:

var codes = codesWithSubCodes.ConvertAll(code => code.Replace(".0", "."));

Code Snippets

if (code.Contains('.'))
    {
        var prefix = code.Split('.')[0];
        var subCode = code.Split('.')[1].TrimStart('0');
        codes.Add(prefix + '.' + subCode);
    }
    else
    {
        codes.Add(code);
    }
var codeSections = code.Split('.');
var code = codeSections[0];

if (codeSections.Length == 2)
    code += "." + codeSections[1].TrimStart('0');

codes.Add(code);
code = code.Replace(".0", ".");
var codes = codesWithSubCodes.ConvertAll(code => code.Replace(".0", "."));

Context

StackExchange Code Review Q#96252, answer score: 8

Revisions (0)

No revisions yet.