views:

112

answers:

1

In my application, a string generated its length can varying from 1 to 100 (not using random number algo). But I want if length is less than 7 than need to add integers 1,2,3.. untill its size reach to 7. I implements it using while loop as :

If generatedUserName.Length < 7 Then
    Dim count As Int32 = 0
    While generatedUserName.Length < 7
        generatedUserName = generatedUserName & count.ToString()
        count = count + 1
    End While
End If

Is any other better way such as enbuild function Tostring() with some parameter?

+6  A: 

The simplest way would be something like:

if (generatedUserName.Length < 7)
{
    generatedUserName = (generatedUserName + "1234567").Substring(0, 7);
}

It's slightly inefficient, but unlikely to cause a bottleneck...

Another alternative would be:

if (generatedUserName.Length < 7)
{
    string suffix = "1234567".Substring(0, 7 - generatedUserName.Length);
    generatedUserName = generatedUserName + suffix;
}

A slightly more efficient (but horrible) way:

private static readonly string[] Suffixes = {
    "1234567", "123456", "12345", "1234", "123", "12", "1"
};
...

if (generatedUserName.Length < 7)
{
    generatedUserName = generatedUserName + Suffixes[generatedUserName.Length];
}
Jon Skeet
Why is the alternative less inefficient? Both solutions create two new strings.
dtb
@dtb: in the 2nd the intermediate string is (0..7 chars) shorter.
Henk Holterman
@Henk Holterman: Does that fall into the category of premature pico-optimizations? Calling it micro-optimization feels overdimensioned :-)
dtb
@dtb: I didn't really suggest the second option as an efficiency saving. It was more that some people might find it more readable.
Jon Skeet