Multiplying strings in C# [duplicate] - c#

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Can I "multiply" a string (in C#)?
In Python I can do this:
>>> i = 3
>>> 'hello' * i
'hellohellohello'
How can I multiply strings in C# similarly to in Python? I could easily do it in a for loop but that gets tedious and non-expressive.
Ultimately I'm writing out to console recursively with an indented level being incremented with each call.
parent
child
child
child
grandchild
And it'd be easiest to just do "\t" * indent.

There is an extension method for it in this post.
public static string Multiply(this string source, int multiplier)
{
StringBuilder sb = new StringBuilder(multiplier * source.Length);
for (int i = 0; i < multiplier; i++)
{
sb.Append(source);
}
return sb.ToString();
}
string s = "</li></ul>".Multiply(10);

If you just need a single character you can do:
new string('\t', i)
See this post for more info.

Here's how I do it...
string value = new string(' ',5).Replace(" ","Apple");

There's nothing built-in to the BCL to do this, but a bit of LINQ can accomplish the task easily enough:
var multiplied = string.Join("", Enumerable.Repeat("hello", 5).ToArray());

int indent = 5;
string s = new string('\t', indent);

One way of doing this is the following - but it's not that nice.
String.Join(String.Empty, Enumerable.Repeat("hello", 3).ToArray())
UPDATE
Ahhhh ... I remeber ... for chars ...
new String('x', 3)

how about with a linq aggregate...
var combined = Enumerable.Repeat("hello", 5).Aggregate("", (agg, current) => agg + current);

There is no such statement in C#; your best bet is probably your own MultiplyString() function.

Per mmyers:
public static string times(this string str, int count)
{
StringBuilder sb = new StringBuilder();
for(int i=0; i<count; i++)
{
sb.Append(str);
}
return sb.ToString();
}

As long as it's only one character that you want to repeat, there is a String constructor that you can use:
string indentation = new String('\t', indent);

I don't think that you can extend System.String with an operator overload, but you could make a string wrapper class to do it.
public class StringWrapper
{
public string Value { get; set; }
public StringWrapper()
{
this.Value = string.Empty;
}
public StringWrapper(string value)
{
this.Value = value;
}
public static StringWrapper operator *(StringWrapper wrapper,
int timesToRepeat)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < timesToRepeat; i++)
{
builder.Append(wrapper.Value);
}
return new StringWrapper(builder.ToString());
}
}
Then call it like...
var helloTimesThree = new StringWrapper("hello") * 3;
And get the value from...
helloTimesThree.Value;
Of course, the sane thing to do would be to have your function track and pass in the current depth and dump tabs out in a for loop based off of that.

if u need string 3 times just do
string x = "hello";
string combined = x + x + x;

Related

Concatenate multiple string using string interpolation in c#

The code I tried:
public void ConcatIntegers() {
string s = "";
for (int i = 0; i <= 5; i++) {
s += i.ToString();
}
Console.WriteLine($ "{s}");
Console.Read();
}
In Above method + is used to concatenate multiple values but I was looking for anyway except join, aggregate, concatenate function, instead of + symbol I want to use string interpolation ($) directly which store concatenated string into a string variable.
string s = "";
for (int i = 0; i <= 5; i++) {
// Some code which use string interpolation to
// concatenat multiple string and that result is stored in s
// variable.
}
Console.WriteLine($ "{s}");
Console.Read();
except join, aggregate, concatenate function, instead of + symbol I want to use string interpolation ($)
directly which store concatenated string into a string variable...
simply try:
string result = string.Empty;
for (var i = 0; i <= 5; i++) result = $"{result}{i}";
Use StringBuilder since if you do that a lot it is much faster
Use AppendFormat
StringBuilder sb = new StringBuilder();
string var1 = "abcd";
string var2 = "efgh";
sb.AppendFormat("example: {0}, {1}", var1, var2);
I would use String Builder to concatenate the string:
Your code after changes:
StringBuilder sb = new StringBuilder();
string s = "";
sb.Append(s);
for (int i = 0; i <= 5; i++)
{
sb.Append(i);
}
Console.WriteLine(sb);
Console.ReadLine();
If you want to concatenate, let's try string.Concat or string.Join; with a little help of Linq (in order to get rid of for loop) we'll get
using System.Linq;
...
// static: we don't use "this" in the method
public static void ConcatIntegers() {
// Concatenate range of 0..5 integers: "012345"
Console.WriteLine(string.Concat(Enumerable
.Range(0, 6))); // 6 - we want 6 numbers: 0..5
Console.Read();
}
In case you want to use some format, string interpolation etc. add Select:
public static void ConcatIntegers() {
// "000102030405" since we apply "d2" format (each number reprsented with 2 digits)
Console.WriteLine(string.Concat(Enumerable
.Range(0, 6)
.Select(i => $"{i:d2}"))); // each item in 2 digits format
Console.Read();
}
I had a similar issue on using string interpolation in string.join
string type1 = "a,b,c";
string[] type2 = new string[3] { "a", "b", "c" };
string result = string.Join(",", $"'{x}'");
In both cases, the output should be 'a','b','c'
how to use string.Join() with string interpolation for array of strings

How to add two strings that are numbers? [duplicate]

This question already has answers here:
Adding numbers to a string?
(5 answers)
Closed 7 years ago.
i am looping through some nodes and getting the charge and adding them together. the charge is of type string though.
first time it loops string charge = "309",
second time it loop string charge = "38";
`Looping through list of nodes
{
saBillDetail.TotalServiceUsage += totalSvcNode.InnerText;
}
`
I would have expected that I could add them together, but they are being concatenated instead like this:
`charge + charge = '30938'`
How can I force these strings to be treated as numbers? and get output like this at the end of the loop
`charge + charge = '347'`
As people allready answered this maybe another solution
So you don't get errors
private static int AddTwoStrings(string one, string two)
{
int iOne = 0;
int iTwo = 0;
Int32.TryParse(one, out iOne);
Int32.TryParse(two, out iTwo);
return iOne + iTwo;
}
Or if you want a string result.
private static String AddTwoStrings(string one, string two)
{
int iOne = 0;
int iTwo = 0;
Int32.TryParse(one, out iOne);
Int32.TryParse(two, out iTwo);
return (iOne + iTwo).ToString();
}
EDIT:
As Alexei Levenkov stated you could/should handle exceptions.
Maybe something like this will help you during development
private static int AddTwoStrings(string one, string two)
{
int iOne = 0;
int iTwo = 0;
bool successParseOne = Int32.TryParse(one, out iOne);
bool successParseTwo = Int32.TryParse(two, out iTwo);
if (!successParseOne)
{
throw new ArgumentException("one");
}
else if(!successParseTwo)
{
throw new ArgumentException("two");
}
return (iOne + iTwo);
}
So when you have a wrong number you will be notified if you use try/catch
You need to parse the numbers from the strings:
string number1 = "309";
string number2 = "38";
int result = int.Parse(number1) + int.Parse(number2);
Then you can set the text equal to that string representation:
string addResult = result.ToString();
Note: Int32.Parse() will throw an exception if the format isn't correct. Consider using Int32.TryParse() for a bool way to capture an impossible parsing.
You will need to convert your strings to integer, add them and convert the result back to string:
int sum = 0;
foreach (string strNumber in strNumberCollection)
{
int number;
if (int.TryParse(strNumber, out number))
sum += number;
}
string total = sum.ToString();

Reverse a String without using Reverse. It works, but why?

Ok, so a friend of mine asked me to help him out with a string reverse method that can be reused without using String.Reverse (it's a homework assignment for him). Now, I did, below is the code. It works. Splendidly actually. Obviously by looking at it you can see the larger the string the longer the time it takes to work. However, my question is WHY does it work? Programming is a lot of trial and error, and I was more pseudocoding than actual coding and it worked lol.
Can someone explain to me how exactly reverse = ch + reverse; is working? I don't understand what is making it go into reverse :/
class Program
{
static void Reverse(string x)
{
string text = x;
string reverse = string.Empty;
foreach (char ch in text)
{
reverse = ch + reverse;
// this shows the building of the new string.
// Console.WriteLine(reverse);
}
Console.WriteLine(reverse);
}
static void Main(string[] args)
{
string comingin;
Console.WriteLine("Write something");
comingin = Console.ReadLine();
Reverse(comingin);
// pause
Console.ReadLine();
}
}
If the string passed through is "hello", the loop will be doing this:
reverse = 'h' + string.Empty
reverse = 'e' + 'h'
reverse = 'l' + 'eh'
until it's equal to
olleh
If your string is My String, then:
Pass 1, reverse = 'M'
Pass 2, reverse = 'yM'
Pass 3, reverse = ' yM'
You're taking each char and saying "that character and tack on what I had before after it".
I think your question has been answered. My reply goes beyond the immediate question and more to the spirit of the exercise. I remember having this task many decades ago in college, when memory and mainframe (yikes!) processing time was at a premium. Our task was to reverse an array or string, which is an array of characters, without creating a 2nd array or string. The spirit of the exercise was to teach one to be mindful of available resources.
In .NET, a string is an immutable object, so I must use a 2nd string. I wrote up 3 more examples to demonstrate different techniques that may be faster than your method, but which shouldn't be used to replace the built-in .NET Replace method. I'm partial to the last one.
// StringBuilder inserting at 0 index
public static string Reverse2(string inputString)
{
var result = new StringBuilder();
foreach (char ch in inputString)
{
result.Insert(0, ch);
}
return result.ToString();
}
// Process inputString backwards and append with StringBuilder
public static string Reverse3(string inputString)
{
var result = new StringBuilder();
for (int i = inputString.Length - 1; i >= 0; i--)
{
result.Append(inputString[i]);
}
return result.ToString();
}
// Convert string to array and swap pertinent items
public static string Reverse4(string inputString)
{
var chars = inputString.ToCharArray();
for (int i = 0; i < (chars.Length/2); i++)
{
var temp = chars[i];
chars[i] = chars[chars.Length - 1 - i];
chars[chars.Length - 1 - i] = temp;
}
return new string(chars);
}
Please imagine that you entrance string is "abc". After that you can see that letters are taken one by one and add to the start of the new string:
reverse = "", ch='a' ==> reverse (ch+reverse) = "a"
reverse= "a", ch='b' ==> reverse (ch+reverse) = b+a = "ba"
reverse= "ba", ch='c' ==> reverse (ch+reverse) = c+ba = "cba"
To test the suggestion by Romoku of using StringBuilder I have produced the following code.
public static void Reverse(string x)
{
string text = x;
string reverse = string.Empty;
foreach (char ch in text)
{
reverse = ch + reverse;
}
Console.WriteLine(reverse);
}
public static void ReverseFast(string x)
{
string text = x;
StringBuilder reverse = new StringBuilder();
for (int i = text.Length - 1; i >= 0; i--)
{
reverse.Append(text[i]);
}
Console.WriteLine(reverse);
}
public static void Main(string[] args)
{
int abcx = 100; // amount of abc's
string abc = "";
for (int i = 0; i < abcx; i++)
abc += "abcdefghijklmnopqrstuvwxyz";
var x = new System.Diagnostics.Stopwatch();
x.Start();
Reverse(abc);
x.Stop();
string ReverseMethod = "Reverse Method: " + x.ElapsedMilliseconds.ToString();
x.Restart();
ReverseFast(abc);
x.Stop();
Console.Clear();
Console.WriteLine("Method | Milliseconds");
Console.WriteLine(ReverseMethod);
Console.WriteLine("ReverseFast Method: " + x.ElapsedMilliseconds.ToString());
System.Console.Read();
}
On my computer these are the speeds I get per amount of alphabet(s).
100 ABC(s)
Reverse ~5-10ms
FastReverse ~5-15ms
1000 ABC(s)
Reverse ~120ms
FastReverse ~20ms
10000 ABC(s)
Reverse ~16,852ms!!!
FastReverse ~262ms
These time results will vary greatly depending on the computer but one thing is for certain if you are processing more than 100k characters you are insane for not using StringBuilder! On the other hand if you are processing less than 2000 characters the overhead from the StringBuilder definitely seems to catch up with its performance boost.

In C#, perform "static" copy into a substring of a StringBuilder object

To build a sparsely populated fixed width record, I would like to copy a string field into a StringBuilder object, starting at a given position. A nice syntax for this would have been
StringBuilder sb = new StringBuilder(' ', 100);
string fieldValue = "12345";
int startPos = 16;
int endPos = startPos + fieldValue.Length - 1;
sb[startPos..endPos] = fieldValue; // no such syntax
I could obviously do this C style, one character at a time:
for (int ii = 0; ii++; ii < fieldValue.Length)
sb[startPos + ii] = fieldValue[ii];
But this seems way too cumbersome for c#, plus it uses a loop where the resulting machine code could more efficiently use a bulk copy, which can make a difference if the strings involved were long. Any ideas for a better way?
Your original algorithm can be supported in the following way
var builder = new StringBuilder(new string(' ', 100));
string toInsert = "HELLO WORLD";
int atIndex = 10;
builder.Remove(atIndex, toInsert.Length);
builder.Insert(atIndex, toInsert);
Debug.Assert(builder.Length == 100);
Debug.Assert(builder.ToString().IndexOf(toInsert) == 10);
You can write your own specialized string builder class that uses the efficient machinery of char[] and string underneath the hood, in particular String.CopyTo:
public class FixedStringBuilder
{
char[] buffer;
public FixedStringBuilder(int length)
{
buffer = new string(' ', length).ToCharArray();
}
public FixedStringBuilder Replace(int index, string value)
{
value.CopyTo(0, buffer, index, value.Length);
return this;
}
public override string ToString()
{
return new string(buffer);
}
}
class Program
{
static void Main(string[] args)
{
FixedStringBuilder sb = new FixedStringBuilder(100);
string fieldValue = "12345";
int startPos = 16;
sb.Replace(startPos, fieldValue);
string buffer = sb.ToString();
}
}
The closest solution to your goal is to convert the source string in a char array, then substitute the cells. Any char array can be converted back to a string.
why are you pre-allocating memory in the string builder (it is only support performance).
i would append the known prefix, then the actual value and then the postfix to the string.
something like:
StringBuilder sb = new StringBuilder();
sb.Append(prefix).Append(value).Append(postfix);

Formatting alphanumeric string

I have a string with 16 alphanumeric characters, e.g. F4194E7CC775F003. I'd like to format it as F419-4E7C-C775-F003.
I tried using
string.Format("{0:####-####-####-####}","F4194E7CC775F003");
but this doesn't work since it's not a numeric value.
So I came up with the following:
public class DashFormatter : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
return this;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
char[] chars = arg.ToString().ToCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chars.Length; i++)
{
if (i > 0 && i % 4 == 0)
{
sb.Append('-');
}
sb.Append(chars[i]);
}
return sb.ToString();
}
}
and by using
string.Format(new DashFormatter(), "{0}", "F4194E7CC775F003");
I was able to solve the problem, however I was hoping there is a better/simpler way to do it? Perhaps some LINQ magic?
Thanks.
You can do it in one line without Linq:
StringBuilder splitMe = new StringBuilder("F4194E7CC775F003");
string joined = splitMe.Insert(12, "-").Insert(8, "-").Insert(4, "-").ToString();
You could do it with a regular expression, though I don't know what the performance of this would be compared to the other methods.
string formattedString = Regex.Replace(yourString, "(\\S{4})\\B", "$1-");
You could put this in an extension method for string too, if you want to do:
yourString.ToDashedFormat();
If you want it linq:
var formatted = string.Join("-", Enumerable.Range(0,4).Select(i=>s.Substring(i*4,4)).ToArray());
And if you want it efficient:
var sb = new StringBuilder(19);
sb.Append(s,0,4);
for(var i = 1; i < 4; i++ )
{
sb.Append('-');
sb.Append(s,i*4, 4);
}
return sb.ToString();
I did not benchmark this one, but i think it would be faster then StringBuilder.Insert because it does not move the rest of string many times, it just writes 4 chars.
Also it would not reallocate the underlying string, because it's preallocated to 19 chars at the beginning.
Based on Carra's answer I made this little utility method:
private static string ToDelimitedString(string input, int position, string delimiter)
{
StringBuilder sb = new StringBuilder(input);
int x = input.Length / position;
while (--x > 0)
{
sb = sb.Insert(x * position, delimiter);
}
return sb.ToString();
}
You can use it like this:
string result = ToDelimitedString("F4194E7CC775F003", 4, "-");
And a test case:
[Test]
public void ReturnsDelimitedString()
{
string input = "F4194E7CC775F003";
string actual = ToDelimitedString(input, 4, "-");
Assert.AreEqual("F419-4E7C-C775-F003", actual);
}
char[] chars = "F4194E7CC775F003".ToCharArray();
var str = string.Format("{0}-{1}-{2}-{3}"
, new string(chars.Take(4).ToArray())
, new string(chars.Skip(4).Take(4).ToArray())
, new string(chars.Skip(8).Take(4).ToArray())
, new string(chars.Skip(12).Take(4).ToArray())
);
Simplest solution I can think of is
var text = "F4194E7CC775F003";
var formattedText = string.Format(
"{0}-{1}-{2}-{3}",
text.Substring(0, 4),
text.Substring(4, 4),
text.Substring(8, 4),
text.Substring(12, 4));
Only 9 years later, a minor variation from Carra's answer. This yields about a 2.5x speed improvement based on my tests (change all "-" to '-'):
StringBuilder initial = new StringBuilder("F4194E7CC775F003");
return initial.Insert(12, '-').Insert(8, '-').Insert(4, '-').ToString();

Categories