help to multiplication

  • Thread starter Thread starter yqyq22
  • Start date Start date
yqyq22 said:
Hi All,
i need to multiple a string * 5
string name = "frank"
name * 5
Thanks a lot


What is the expected result? The string repeated five times? If that's
the case, you can do it by appending the text inside a loop. For efficiency
(in case the multiplier is relatively large) you should probably use a
StringBuilder:

private static string Multiply(this string s, int n)
{
StringBuilder sb = new StringBuilder();
for (int i=0; i<n; i++)
{
sb.Append(s);
}
return sb.ToString();
}

Invoke it thus:

string name = "frank";
string result = name.Multiply(5);

Note that my example is an Extension method, which requires C# 3.0. If you
are using an earlier version, you can remove the "this" from the parameters
to turn it into a normal method.
 
    What is the expected result? The string repeated five times? If that's
the case, you can do it by appending the text inside a loop. For efficiency
(in case the multiplier is relatively large) you should probably use a
StringBuilder:

private static string Multiply(this string s, int n)
{
    StringBuilder sb = new StringBuilder();
    for (int i=0; i<n; i++)
    {
        sb.Append(s);
    }
    return sb.ToString();

}

Invoke it thus:

string name = "frank";
string result = name.Multiply(5);

Note that my example is an Extension method, which requires C# 3.0. If you
are using an earlier version, you can remove the "this" from the parameters
to turn it into a normal method.

thanks a lot (this is also very helpfull)
 
yqyq22 said:
Solved.. thanks.. i means
string bmulti = new string('b', 5);

Here you are multiplying a char not a string.

For string you need a loop like the one Alberto showed.

But let me guess: Python programmer?

Arne
 
Here you are multiplying a char not a string.

For string you need a loop like the one Alberto showed.

But let me guess: Python programmer?

Arne

Yes.. sometime i try to write some little script in Python, but i
didn't undestand Alberto Example because I'm using .net 2.0, and also
if i remove the [this] keyword i dont' find other useful methods...or
better i don't know which method i should use...
Could you help me?
thanks in advance for your kindness
 
yqyq22 said:
Here you are multiplying a char not a string.

For string you need a loop like the one Alberto showed.

But let me guess: Python programmer?

Yes.. sometime i try to write some little script in Python, but i
didn't undestand Alberto Example because I'm using .net 2.0, and also
if i remove the [this] keyword i dont' find other useful methods...or
better i don't know which method i should use...
Could you help me?

..NET 3.5 allows:

private static string Multiply(this string s, int n)

string result = name.Multiply(5);

In .NET 2.0 you will need to:

private static string Multiply(string s, int n)

string result = name.Multiply(name, 5);

Arne
 
Back
Top