C# add new text to string WITHOUT copy it previous value [duplicate] - c#

This question already has answers here:
Most efficient way to concatenate strings?
(18 answers)
Closed 3 years ago.
I have string that i need to combine with another string , for example
string string1 = "cars"; // the text is just for example
string string2 = "white";
// then
string string1 = string1 + string2;
// or
string string1 += string2;
Alright , at first glance it doesn't have any problem right ?
NOPE , it does have problem
when the string.length / the string contain A LOT OF CHARACTER , for example when it contain 100.000 word , it start to get laggy or freeze when i put it inside loop, because it need to copy 100.000 word plus word from the other string everytime it combines string1 with string2 .
Is the any alternative way to add new text to string that contain massive amount of word ?

The correct way to accumulate strings in c# is using StringBuilder.
Example:
StringBuilder sb = new StringBuilder();
sb.Append("...");
sb.Append("...");
....
var result = sb.ToString()
Your solution appear to lag, since every time you "modify" a string a brand new one is created instead, so the garbage collector get a little crazy...

Related

C# only use arrays if it exists

I am a beginner in programming. And now I'm facing a task where I can't get any further. Probably it is relatively easy to solve.
This is what I want to do: I read out a .txt file and there are several lines of content.
Example what is in the .txt file:
text1,text2,text3
text1,text2,
text1,text2,text3,text4
I'm now ready to find the right line and use it. Then I want to split the line and assign each text to its own string.
I can do this if I know that this line have 4 words. But what if I don't know how many words this line have.
For example if I want to assign 5 strings but there are only 4 arrays in the column I get an error.
My program currently looks like this:
string reader = "text1,text2,text3,text4";
string[] words = reader.Split(',');
string word1 = words[0].ToString();
string word2 = words[1].ToString();
string word3 = words[2].ToString();
string word4 = words[3].ToString();
textBox1.Text = word3;
My goal is to find out how many words are in the string. And then pass each word to a separate string.
Thank you in advance
To get the length of the Array, you can easily use .Length
In your example, you just write
int arraylength = words.Length;
I don't understand, why do you want to create a new String for every value of the string-array? You can just use them in the array.
In your example you always user .ToString(), this isn't necessary because you already have a string.
An array is just multiple variables (in your example strings) which are connected to another.
I doubt if you want separated local variables like word1, word2 etc. To see why, let's
bring the idea to the point of absurdity. Imagine, that we have a small narration with 1234
words only. Do we really want to create word1, word2, ..., word1234 local variables?
So, let's stick to a single words array only:
string[] words = reader.Split(',');
Now, you can easily get array Length (i.e. number of items):
textBoxCount.Text = $"We have {words.Length} words in total";
Or get N-th word (let N be one based) from the words array:
string wordN = array.Length >= N ? array[N - 1] : "SomeDefaultValue";
In your case (3d word) it can be
// either 3d word or an empty string (when we have just two less words)
textBox1.Text = array.Length >= 3 ? array[3 - 1] : "";
Technically, you can use Linq and query the reader string:
using System.Linq;
...
// 3d word or empty string
textBox1.Text = reader.Split(',').ElementAtOrDefault(3 - 1) ?? "";
But Linq seems to be overshot here.

Is it possible to convert Hello.World to ["Hello"]["World"]? [duplicate]

This question already has answers here:
Put result of String.Split() into ArrayList or Stack
(5 answers)
Closed 2 years ago.
I was wondering if there is a way to convert example:
'Hello.World' into '["Hello"]["World"]' or 'This.is.a.string' into ["This"]["is"]["a"]["string"]
I'm kinda new to C# and I was wondering if that's even possible using string formatting or something like that.
You can use the Split method like this string[] strings = String.Split("."); This will split your string per each period.
If you meant to include the single quotes (') as part of the string then:
String test = "'Hello.World'";
// Strip the first and last '
test = test.Substring(1, test.Length - 2);
// Split on Period
String[] split = test.Split('.');
// Encapsulate each word with [" "]
// and add back in the single quotes
var result = $"'{String.Join("", split.Select(word => $"[\"{word}\"]"))}'";
Prints:
'["Hello"]["World"]'
If they just meant to surround your input then just:
String test = "Hello.World";
// Split on Period
String[] split = test.Split('.');
// Encapsulate each word with [" "]
var result = $"{String.Join("", split.Select(word => $"[\"{word}\"]"))}";
Prints: ["Hello"]["World"]

How can i filter a string by first few char [duplicate]

This question already has answers here:
To get specific part of a string in c# [closed]
(5 answers)
Closed 4 years ago.
I have a string variable called price which contains a range of price pattern as you can see in code. I want to filter it by its first part only.
string price = "9.99 - 12.99";
i already tried like bellow but this gives me wrong output something like ".99" however this is not my target output i am looking for.
string result = price.Substring(1, price.IndexOf("-") - 1);
The output i want like this- "9.99". Now can i filter this part from that string? Thanks in advance
Strings in C# are zero-based, so when you set the starting character as 1, you're in fact starting from the second character. Just use 0 and you should be OK:
string result = price.Substring(0, price.IndexOf("-") - 1);
Note, by the way, that you could use the full " - " delimiter instead of playing around with index arithmetic:
string result = price.Substring(0, price.IndexOf(" - "));
You're close but note that strings are 0 indexed:
string result = price.Substring(0, price.IndexOf("-") - 1);

How to remove space from DateTime in C#? [duplicate]

This question already has answers here:
C# DateTime to "YYYYMMDDHHMMSS" format
(18 answers)
Closed 5 years ago.
I developing a xamarin form app and I am assigning the current date time as a Filename for image. Currently the image is saved as "7202017 53150 PM.jpg". I want it to be saved like this "720201753150PM.jpg". How can I remove the space between the date and time?
I tried like below but it did not work.
string _imagename = DateTime.Now.ToString();
_imagename.Replace(" ", string.Empty);
Actually the String.Replace() Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string(in short it won't change the actual string) So you need to assign the result to another variable. And perform the replace operation there.
But Why you go for another replace? whynot use .ToString() like the following?
string format = "Mddyyyyhhmmsstt";
string _imagename = String.Format("{0}.jpg",DateTime.Now.ToString(format))
You need to assign the new value as string is immutable:
string _imagename = DateTime.Now.ToString();
_imagename = _imagename.Replace(" ", string.Empty);
This is fastest way I know:
Regex.Replace(_imagename, #"\s+", "")
Looking at your string ill also suggest replace spaces with a empty string. And you could do it by applying built in Replace method:
string _imagename = DateTime.Now.ToString();
_imagename = _imagename.Replace(" ", string.Empty);
If you want to order by file name I'd suggest to use a notation like yyyyMMddHHmmss. That way, with increasing date/time the sort order will also increase.
Other than that, strings are immutable in c#. Thus calling Replace does not change the original string. You need to assign the result to your variable as #Romano Zumbé pointed out.
You can just use a format string like the following (including the sorting suggestion):
string imagename = $"{DateTime.Now:yyyyMMddHHmmss}.jpg";
otherwise it would be:
string imagename = $"{DateTime.Now:Mddyyyyhmmsstt}.jpg";

Capitalizing the first letter of a string only [duplicate]

This question already has answers here:
Make first letter of a string upper case (with maximum performance)
(42 answers)
Closed 7 years ago.
I have already taken a look at such posts like:
Format to first letter uppercase
How to capitalise the first letter of every word in a string
But none of these seem to actually work. I would have thought to start with that there would just be a:
.Capitalize();
Like there is:
.Lower(); & .Upper();
Are there any documentation or references regarding converting to a string like the following?
string before = "INVOICE";
To then becoming:
string after = "Invoice";
I receive no errors using the way the posts solutions I read give me, however, the before still remains capitalized.
What about using ToUpper on the first char and ToLower on the remaining string?
string after = char.ToUpper(before.First()) + before.Substring(1).ToLower();
You can create a method that does something like this:
string UppercaseFirst(string str)
{
if (string.IsNullOrEmpty(str))
return string.Empty;
return char.ToUpper(str[0]) + str.Substring(1).ToLower();
}
And use it like this:
string str = "thISstringLOokSHorribLE";
string upstr = UppercaseFirst(str);
to get this:
Thisstringlookshorrible

Categories

Resources