extend Stringbuilder to append array - c#

Still new to the extension methods. According to this guide, it is still unclear to me how I can append an array just like appending a string with Append(). Can anyone provide me with a small example?
int a = 2;
object obj = XXXXX;
StringBuilder sb = new StringBuilder();
sb.Append(a);
sb.Append(obj);
Basically the type of obj is unknown it could be int[], char[]..., I am trying to reuse Append() to make it more generalized to handle array types so the
sb.ToString()
will output the whole thing I have appended

Related

What is the best way to copy a StringBuilder?

What is the best way (performance wise) to instantiate a new StringBuilder from another one? (Copy-Ctor).
I don't want to pass via an immutable string as the underneath data is very big.
so the below is valid, but not wanted.
StringBuilder newSB = new StringBuilder(oldSB.ToString());
I want something like
StringBuilder newSB = new StringBuilder(oldSB);
But this is not supported.
There’s an overload of Append for other StringBuilder instances:
var newSB = new StringBuilder(oldSB.Length);
newSB.Append(oldSB);

.NET Core 2.1 string.Create

I use string.Create method to create a new string like this:
var rawStr = "raw str";
var newStr = string.Create(rawStr.Length, rawStr,
(chars, str) =>
{
chars = str.ToCharArray();
});
but, the result newStr just an empty char array.
I saw an answer here, and modify my code:
var rawStr = "raw str";
var newStr = string.Create(rawStr.Length, rawStr.ToCharArray(),
(chars, str) =>
{
//chars = str.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
chars[i] = str[i];
}
});
Then, newStr's value is raw str, this is why?
I'll try to explain what you are doing:
String.Create documentation
Creates a new string with a specific length and initializes it after creation by using the specified callback.
What you can achieve with the create, is a kind of conversion. In it's simplest form, it just takes an array of chars and creates as string.
Let's break down the function:
string.Create<TType>( newStrLength, typedOnject, creationFunction);
TType - It's the input type (in your case as string) that will be converted or used to create the new string
newStrLength - You need to provide the new string length
typedOnject - Object of type TType that will be given to the creation function
creationFunction - A lamda function that will do something based on the characters and the TType buffer. Create is calling this function. The chars are being provided by the Create and they are the new string's chars to modify as you please.
In your case, you creation function gets one by one the characters from the string and maps them to a new string, creating effectively a copy of one.
In your first attempt the following happens:
The chars array has a reference that is replaced by your new array that the ToCharArray returns. So by this assignment you are no longer referencing the characters that will be used to create the string. The original array remains unchanged.
In the second attempt you are changing the values of the original array and thus the new string uses it.
There is no need in this complexity. Use this syntax:
var rawStr = "raw str";
var newStr = rawStr;

Add into string field [duplicate]

This question already has an answer here:
String Concatenation using '+' operator
(1 answer)
Closed 8 years ago.
tell me pls what's problem with this code C#.
string str = string.Empty;
for (var i = 1; i <= 1000; i++)
str += i.ToString();
This was interview question.
actually there is no problem with your code.
inthis case StringBuilder is more appropriate than string.
because StringBuilder is mutable whereas string is immutable.
so whenever you modify the String object using += it creates a new string object so at the end of your loop it creates many string objects.
but if you use StringBuilder: same object will be modified each time you Append the Strings to it.
You can find more info from MSDN: StringBuilder Class
The String object is immutable. Every time you use one of the methods
in the System.String class, you create a new string object in memory,
which requires a new allocation of space for that new object. In
situations where you need to perform repeated modifications to a
string, the overhead associated with creating a new String object can
be costly. The System.Text.StringBuilder class can be used when you
want to modify a string without creating a new object. For example,
using the StringBuilder class can boost performance when concatenating
many strings together in a loop.
Solution :
This
string str = string.Empty;
for (var i = 1; i <= 1000; i++)
str += i.ToString();
Shouldbe this
StringBuilder str =new StringBuilder();
for (var i = 1; i <= 1000; i++)
str.Append(i.ToString());
There is an answer here.
the compiler can't do anything if you concatenate in a loop and this does generate a lot of garbage.

Performance considerations for String and StringBuilder - C#

All,
For the string string s = "abcd", does string w = s.SubString(2) return a new allocated String object i.e. string w = new String ("cd") internally or a String literal?
For StringBuilder, when appending string values and if the size of the StringBuilder needs to be increased, are all the contents copied over to a new memory location or simply the pointers to each of the earlier String value are reassigned to the new location?
String is immutable, so any operation that "changes" the string, will in effect return a new string. This includes SubString and all other operations on String, including those that does not change the length (such as ToLower() or similar).
StringBuilder contains internally a linked list of chunks of characters. When it needs to grow, a new chunk is allocated and inserted at the end of the list, and data is copied here. In other words, the whole StringBuilder buffer will not be copied on an append, only the data you are appending. I double-checked this against the Framework 4 reference sources.
For the string string s = "abcd", does string w = s.SubString(2) return a new allocated String object? Yes
For StringBuilder, when appending string values and if the size of the StringBuilder needs to be increased, are all the contents copied over to a new memory location? Yes
Any change in String small or large results in a new String
If you are going to make large numbers of edits to a string it better to do this via StringBuilder.
From MSDN:
You can use the StringBuilder class instead of the String class for operations that make multiple changes to the value of a string. Unlike instances of the String class, StringBuilder objects are mutable; when you concatenate, append, or delete substrings from a string, the operations are performed on a single string.
Strings are immutable objects so every time you had to make changes you create a new instance of that string. The substring method does not change the value of the original string.
Regards.
Difference between the String and StringBuilder is an important concept which makes the difference when an application has to deal with the editing of a high number of Strings.
String
The String object is a collection of UTF-16 code units represented by a System.Char object which belong to the System namespace. Since the value of this objects are read-only, the entire object String has defined as immutable. The maximum size of a String object in memory is 2 GB, or about 1 billion characters.
Immutable
Being immutable means that every time a methods of the System.String is used, a new sting object is created in memory and this cause a new allocation of space for the new object.
Example:
By using the string concatenation operator += appears that the value of the string variable named test change. In fact, it create a new String object, which has a different value and address from the original and assign it to the test variable.
string test;
test += "red"; // a new object string is created
test += "coding"; // a new object string is created
test += "planet"; // a new object string is created
StringBuilder
The StringBuilder is a dynamic object which belong to the System.Text namespace and allow to modify the number of characters in the string that it encapsulates, this characteristic is called mutability.
Mutability
To be able to append, remove, replace or insert characters, A StringBuilder maintains a buffer to accommodate expansions to the string. If new data is appended to the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, and the new data is then appended to the new buffer.
StringBuilder sb = new StringBuilder("");
sb.Append("red");
sb.Append("blue");
sb.Append("green ");
string colors = sb.ToString();
Performances
In order to help you better understand the performance difference between String and StringBuilder, I created the following example:
Stopwatch timer = new Stopwatch();
string str = string.Empty;
timer.Start();
for (int i = 0; i < 10000; i++) {
str += i.ToString();
}
timer.Stop();
Console.WriteLine("String : {0}", timer.Elapsed);
timer.Restart();
StringBuilder sbr = new StringBuilder(string.Empty);
for (int i = 0; i < 10000; i++) {
sbr.Append(i.ToString());
}
timer.Stop();
Console.WriteLine("StringBuilder : {0}", timer.Elapsed);
The output is
Output
String : 00:00:00.0706661
StringBuilder : 00:00:00.0012373

Display array values from web service method

I'm new to web services and im actually trying to learn how to develop one in C#.
I have the following method in my web service which actually displays an array of int when i test it.
[WebMethod]
public int[] FindID(string str1,string str2)
{
Customer obj = new Customer();
obj.FindMatch(str1,str2);
return obj.customer_id;
}
Now in my web application in which i have a button, the code is as below:
Dim obj As localhost.Service = New localhost.Service
Dim str1 As String = Session("str1")
Dim str2 As String = Session("str2")
Response.Write(obj.FindID(str1, str2))
The problem is that only the first value from the array is being displayed. Can anyone please help me to solve this problem?
You could also use String.Join() http://msdn.microsoft.com/en-us/library/57a79xd0.aspx which takes a delimiter and an array of strings, and returns a single string containing the original strings inside the array, delimited by your delimiter.
This can be achieved very simply:
Console.WriteLine(", ", string.Join(obj.FindID(str1, str2)));
Console.Write displays only a single value such an integer, a float number or a string. It will never walk through an array to display each value.
Instead, you can call a Console.Write on each entry in your array.
foreach (int value in obj.FindID(str1, str2))
{
Console.WriteLine(value.ToString());
}
Note that calling Console.Write is resource expensive. If you need to display values of a very long array, maybe you will achieve better results by using StringBuilder class, then calling Console.Write once.
StringBuilder stringBuilder = new StringBuilder();
foreach (int value in obj.FindID(str1, str2))
{
stringBuilder.AppendLine(value.ToString());
}
// Call this once.
Console.Write(stringBuilder.ToString());

Categories

Resources