C# - Very slow string variable calculation - c#

I have over 27,000,000 string variable in the array. When I add a string to another one speed is greatly reduced. my code is:
//public string[] part2 = { .....
string Str1;
string Str0;
Parallel.ForEach(index_choose, x =>
{
Str1 += part1[x];
Str0 += part2[x];
//progressBar1.PerformStep();
//label1.Text = progressBar1.Value.ToString();
//Application.DoEvents();
});
string total = Str1 + Str0;
Run this code on a powerful CPU takes More than 20 hours!

I will recommend to use StringBuilder - like in the following example
StringBuilder str0 = new StringBuilder();
StringBuilder str1 = new StringBuilder();
Parallel.ForEach(index_choose, x =>
{
Str1.Append(part1[x]);
Str0.Append(part2[x]);
//progressBar1.PerformStep();
//label1.Text = progressBar1.Value.ToString();
//Application.DoEvents();
});
string total = Str1.Append(Str0).ToString();

Related

Converting a range of strings to int for addition

This is an extension of the question asked here:
Converting string to int and then back to string
I am now converting a range of string values to add all of them together. I obviously cannot do something like:
int Total;
string str1 = "1";
string str2 = "1";
string str3 = "1";
string str4 = "1";
string str5 = "1";
string str6 = "1";
...
...
void Start()
{
Total = int.Parse(str1) + int.Parse(str2) + .....
}
I am looking for a way to parse all the strings into int such that:
Total = int.Parse(str1 + str2 + str3 + ...)
How do I achieve this?
As long as you do not know how many values you will have, you cannot hardcode all the single values into independent variables.
Advice: You should really consider storing the data in the correct format, You approach should be working with integers instead of strings (using a List<int>). The code would be more bug resistant and more simple.
int Total = 0;
List<string> valuesToAdd = new List<string>(){
"1",
"4",
"1",
"99"
};
void Start()
{
Total = 0;
foreach(string stringValue in valuesToAdd)
{
Total += int.Parse(stringValue);
}
}

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

string reverse in C#

For example, my input is my name is abcd
I need to display as dcba si eman ym
I have done below which is giving an output as abcd is name my
but have no idea what to do next
static void Main(string[] args)
{
Console.WriteLine("Enter a string: ");
string[] input = Console.ReadLine().Split(' ');
for (int i = input.Length-1; i >=0; i--)
{
Console.Write(input[i]+" ");
}
Console.ReadKey();
}
You can use the API - Array.Reverse
char[] charArray = input.ToCharArray();
Array.Reverse( charArray );
reversed = new string( charArray );
Try this this will work perfectly. I think this is what you have been looking for!
string Str, reversestring = "";
int Length;
Console.Write("Enter A String : ");
Str = Console.ReadLine();
Length = Str.Length - 1;
while (Length >= 0)
{
reversestring = reversestring + Str[Length];
Length--;
}
Console.WriteLine("Reverse String Is {0}", reversestring);
Console.ReadLine();
My Fiddle example: Reverse with Words and Text
You don't need the .Split(' ') in string[] input = Console.ReadLine().Split(' ');
You can simply read the entire line with string input = Console.ReadLine(); then reverse the entire line.
If you look at the below link it provides two options.
Reverse the entire string using a Array.Reverse
loop through every character from the end to the start and output it.
https://www.dotnetperls.com/reverse-string#d
What your code do is reversing the initial string by words, like this:
my name is abcd --> abcd is name my
To change this you need to read the whole string and use it as char array:
var input = Console.ReadLine();
var sb = new StringBuilder(input.Length);
for (var i = input.Length - 1; i >= 0; --i)
{
sb.Append(input[i]);
}
Console.WriteLine(sb.ToString());
Also you can use the Array.Reverse method:
var input = Console.ReadLine();
var charArray = input.ToCharArray();
Array.Reverse(charArray);
var reversed = new string(charArray);
Console.WriteLine(reversed);
You can use LINQ's Aggregate function to reverse a string
Console.WriteLine("Enter a string: ");
string input = Console.ReadLine();
input = input.Aggregate(new StringBuilder(), (j, k) => j.Insert(0, k)).ToString();
The Aggregate prepend each Char to the reversed string
public static string RevString(string str)
{
var charArry = str.ToCharArray();
Array.Reverse(charArry);
return new string(charArry);
}
public static string RevString2(string str)
{
string revString = "";
foreach( char c in str)
{
revString = c + revString;
}
return revString;
}
//no change to the order of the words
public static string RevString3(string str)
{
string[] strArray = str.Split(' ');
string revString = "";
foreach (string s in strArray)
{
var charArray = s.ToCharArray();
Array.Reverse(charArray);
revString += new string(charArray) + " ";
}
return revString;
}
public static string RevString4(string str)
{
string[] strArray = str.Split(' ');
string revString = "";
foreach (string s in strArray)
{
string revWord = "";
foreach(char c in s)
{
revWord = c + revWord;
}
revString += revWord + " ";
}
return revString;
}

String Reverse : reversing only position of the Words in String in c#

original String is "Hello World"
Output Should be "World Hello"
What is the optimized way to do it in c# ?
Please suggest me any existing link if i am missing
var s = "Hello world";
var result = String.Join(" ", s.Split(' ').Reverse()));
OR (better split below if you ar not sure of your data)
var s = "Hello world";
var result = String.Join(" ", Regex.Split(s, #"\s").Reverse());
I would split the sentence by the words (the space between them):
string[] words = helloString.Split(" ");
helloString = words[1] + " " + words[0];
You could optimise this to work with any sentence with any number of words by looping through words from the last element to the first.
I've reassigned the new string back to helloString (the original) as I assume this is what you want based on the question.
Try This Code :
string value = "Hello world";
string firstvalue = value.Split(' ').First();
string secvalue = value.Split(' ').Last();
string value = secvalue + firstvalue;
static void Main(string[] args)
{
String str = "Hello World";
String[] strNames = str.Split(' ');
for(int i=strNames.Length-1;i>=0;i--)
Console.Write(strNames[i]+" ");
}
char[] Delimiter = new char[] { ' ' }
string[] t = string.split("Hello Wordl", Delimiter)
int lenS = t.Count;
string result = "";
for(int x =t-1; t > -1; t--)
{
result += t[x] + " ";
}
//Used result now

How can I delete the first n lines in a string in C#?

How can I delete the first n lines in a string?
Example:
String str = #"a
b
c
d
e";
String output = DeleteLines(str, 2)
//Output is "c
//d
//e"
You can use LINQ:
String str = #"a
b
c
d
e";
int n = 2;
string[] lines = str
.Split(Environment.NewLine.ToCharArray())
.Skip(n)
.ToArray();
string output = string.Join(Environment.NewLine, lines);
// Output is
// "c
// d
// e"
If you need to take into account "\r\n" and "\r" and "\n" it's better to use the following regex:
public static class StringExtensions
{
public static string RemoveFirstLines(string text, int linesCount)
{
var lines = Regex.Split(text, "\r\n|\r|\n").Skip(linesCount);
return string.Join(Environment.NewLine, lines.ToArray());
}
}
Here are some more details about splitting text into lines.
Combination of Get the index of the nth occurrence of a string? (search for Environment.NewLine) and substring should do the trick.
Try the following:
public static string DeleteLines(string s, int linesToRemove)
{
return s.Split(Environment.NewLine.ToCharArray(),
linesToRemove + 1
).Skip(linesToRemove)
.FirstOrDefault();
}
the next example:
string str = #"a
b
c
d
e";
string output = DeleteLines(str, 2);
returns
c
d
e
Try this:
public static string DeleteLines (string text, int lineCount) {
while (text.Split('\n').Length > lineCount)
text = text.Remove(0, text.Split('\n')[0].Length + 1);
return text;
}
It might not be very efficient but it works perfectly for the little project i've been working on recently
Try the following:
private static string DeleteLines(string input, int lines)
{
var result = input;
for(var i = 0; i < lines; i++)
{
var idx = result.IndexOf('\n');
if (idx < 0)
{
// do what you want when there are less than the required lines
return string.Empty;
}
result = result.Substring(idx+1);
}
return result;
}
Note: This method is not ideal for extremely long multi-line strings as it does not consider memory management. If dealing with these kind of strings, I suggest you alter the method to use the StringBuilder class.
With ability to delete first n lines or last n lines:
public static string DeleteLines(
string stringToRemoveLinesFrom,
int numberOfLinesToRemove,
bool startFromBottom = false) {
string toReturn = "";
string[] allLines = stringToRemoveLinesFrom.Split(
separator: Environment.NewLine.ToCharArray(),
options: StringSplitOptions.RemoveEmptyEntries);
if (startFromBottom)
toReturn = String.Join(Environment.NewLine, allLines.Take(allLines.Length - numberOfLinesToRemove));
else
toReturn = String.Join(Environment.NewLine, allLines.Skip(numberOfLinesToRemove));
return toReturn;
}
public static string DeleteLines(string input, int linesToSkip)
{
int startIndex = 0;
for (int i = 0; i < linesToSkip; ++i)
startIndex = input.IndexOf('\n', startIndex) + 1;
return input.Substring(startIndex);
}

Categories