convert string array to string - c#

I would like to convert a string array to a single string.
string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
I would like to have something like "Hello World!"

string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
string.Join("", test);

A slightly faster option than using the already mentioned use of the Join() method is the Concat() method. It doesn't require an empty delimiter parameter as Join() does. Example:
string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
string result = String.Concat(test);
hence it is likely faster.

A simple string.Concat() is what you need.
string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
string result = string.Concat(test);
If you also need to add a seperator (space, comma etc) then, string.Join() should be used.
string[] test = new string[2];
test[0] = "Red";
test[1] = "Blue";
string result = string.Join(",", test);
If you have to perform this on a string array with hundereds of elements than string.Join() is better by performace point of view. Just give a "" (blank) argument as seperator. StringBuilder can also be used for sake of performance, but it will make code a bit longer.

Try:
String.Join("", test);
which should return a string joining the two elements together. "" indicates that you want the strings joined together without any separators.

In the accepted answer, String.Join isn't best practice per its usage. String.Concat should have be used since OP included a trailing space in the first item: "Hello " (instead of using a null delimiter).
However, since OP asked for the result "Hello World!", String.Join is still the appropriate method, but the trailing whitespace should be moved to the delimiter instead.
// string[] test = new string[2];
// test[0] = "Hello ";
// test[1] = "World!";
string[] test = { "Hello", "World" }; // Alternative array creation syntax
string result = String.Join(" ", test);

Aggregate can also be used for same.
string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
string joinedString = test.Aggregate((prev, current) => prev + " " + current);

string ConvertStringArrayToString(string[] array)
{
//
// Concatenate all the elements into a StringBuilder.
//
StringBuilder strinbuilder = new StringBuilder();
foreach (string value in array)
{
strinbuilder.Append(value);
strinbuilder.Append(' ');
}
return strinbuilder.ToString();
}

I used this way to make my project faster:
RichTextBox rcbCatalyst = new RichTextBox()
{
Lines = arrayString
};
string text = rcbCatalyst.Text;
rcbCatalyst.Dispose();
return text;
RichTextBox.Text will automatically convert your array to a multiline string!

Like this:
string str= test[0]+test[1];
You can also use a loop:
for(int i=0; i<2; i++)
str += test[i];

Related

Split String with multiple delimiters to different arrays in c#

So I have a text file copied into memory that is delimited as follows:
"425,9856\n852,9658\n"
This is a long string with some 30,000 entries in total. What I want to do is create two arrays, one for the value to the left of the comma, one for the value to the right of the comma, and then to each array respectively i want to append the next two comma delimited strings that come after the "\n".
I have tried splitting using .Split and passing two delimiting values, but it obviously just creates one array with all values sequentially. Such as:
425
9856
852
9658
When what I want is:
array1:
452
852
array2:
9856
9658
Does that make sense?
many thanks
Since you're reading from a file, why not stream the input line-by-line, rather than reading the whole lot into memory in one go?
using var reader = new StreamReader(filePath);
while (reader.ReadLine() is not null line)
{
// Each line is of the form '425,9856', so just split on the comma
var parts = line.Split(',');
firstList.Add(parts[0]);
secondList.Add(parts[1]);
}
You can just split it twice to get what you want
public static void Main()
{
var foo = "425,9856" + Environment.NewLine + "852,9658" + Environment.NewLine;
var array1 = new List<string>();
var array2 = new List<string>();
string[] lines = foo.Split(
new string[] { Environment.NewLine },
StringSplitOptions.None);
foreach(var line in lines)
{
//Console.WriteLine("line: " + line);
var lineSplit = line.Split(',');
//Console.WriteLine("lineSplit: " + lineSplit.Length);
//lineSplit.Dump();
if(lineSplit.Length > 1)
{
array1.Add(lineSplit[0]);
array2.Add(lineSplit[1]);
}
}
Console.WriteLine("Array1: ");
array1.Dump();
Console.WriteLine("Array2: ");
array2.Dump();
}
And here's a working fiddle of it.
You can use RegEx
string row = #"425,9856\n852,9658\n";
string left = #"[^|(?<=n)]\d*(?=,)";
string right = #"(?<=,)\d*(?=\\)";
Regex rgLeft = new Regex(left);
var l = rgLeft.Matches(row).Select(p=> p.Value);
Regex rgRight = new Regex(right);
var r = rgRight.Matches(row).Select(p=> p.Value);

String.join array from last element

I have a scenario where I am getting a comma separated string LastName, FirstName. I have to convert it into FirstName LastName.
My code is below:
Public static void main(string [] args)
{
var str = "Lastname, FirstName":
var strArr = str.Split(',');
Array. Reverse(strArr);
var output = string.join(" ", strArr);
}
Is there a better way to do this, like in one line or using LINQ?
Yes there is already a Reverse extension method for IEnumerables:
var output = string.Join(" ",str.Split(',').Reverse());
This takes care of a lot of the various edge cases. You mentioned one but did not include it in your initial question so I assume there could be others.
var tests = new[]{"Lastname, FirstName", "Lastname, ", ", FirstName", "Lastname", "FirstName"};
foreach(var str in tests)
{
var strArr = str.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
.Where(x => !string.IsNullOrWhiteSpace(x))
.Reverse()
.Select(x => x.Trim());
var output = string.Join(" ", strArr);
Console.WriteLine(output);
}
Working Fiddle
Use Aggregate and Trim your names after splitting, you do not need reversing.
str.Split(',').Aggregate((lname, fname) => fname.Trim() + " " + lname.Trim())
Below is my new code:
Public static void main(string [] args)
{
var str = "Lastname, FirstName":
var strArr = str.Split(',').Select(p=>p.Trim()).ToArray();
var output = string.join(" ", strArr.Reverse());
}

Creating function syntax by manipulating string

I am trying to create dynamic syntax function and function syntax is like below:
MyFunction( arg1,arg2,ar3.....);
I have string like this:
str = Previousvalue.Value1,Previousvalue.Value2
Now I would like to create syntax like this in final variable :
String final = MyFunction(Previousvalue.Value1,',',Previousvalue.Value2);
str = Previousvalue.Value1,Previousvalue.Value2,Previousvalue.Value3;
String final = MyFunction(Previousvalue.Value1,',',Previousvalue.Value2,',',Previousvalue.Value3);
This is how I am trying to achieve with string.join (without using loop) but not getting how to do it and this seems like impossible to do without using loop:
final = string.Join("MyFunction(", str.Split(','));
Case 1:
Input : string str =Previousvalue.Value1,Previousvalue.Value2
Output:
string final=MyFunction(Previousvalue.Value1,',',Previousvalue.Value2,',',Previousvalue.Value3);
Case 2 :
Input : str = Previousvalue.Value1,Previousvalue.Value2,Previousvalue.Value3;
output:
String final = MyFunction(Previousvalue.Value1,',',Previousvalue.Value2,',',Previousvalue.Value3);
Case 3:
string input = " Previousvalue.Value1";
Output:
String final = Previousvalue.Value1; //No function
From what I understand, you want to generate a string like this:
"MyFunction(Previousvalue.Value1,',',Previousvalue.Value2);"
^..........^...................^....^...................^.
prefix arg1 sep arg2 suffix
or in other words
prefix = "MyFunction(";
separator = ",',',";
suffix = ");"
which can be achieved by moving the prefix and suffix out of the string.Join and using the above separator value:
string final = "MyFunction(" + string.Join(",',',", str.Split(',')) + ");";
Also instead of Split / Join you could simply use string.Replace:
string final = "MyFunction(" + str.Replace(",", ",',',") + ");";
From my understanding of the problem you want to call the MyFunction method with n string parameters, but also with string[]. You can do it like this:
public static void Main(string[] args)
{
string str = "Test1,Test2,Test3";
string test1 = MyFunction("Test1", "Test2", "Test3");
string test2 = MyFunction(str.Split(','));
}
public static string MyFunction(params string[] parameters)
{
StringBuilder sb = new StringBuilder();
foreach(var item in parameters)
{
sb.AppendLine(item);
}
return sb.ToString();
}
Try :
public string MyJoin(params string[] vars)
{
return "MyFunction(" + string.Join(",", vars) + ");";
}

Adding chars before and after each word in a string

Imagine we have a string as :
String mystring = "A,B,C,D";
I would like to add an apostrophe before and after each word in my string.Such as:
"'A','B','C','D'"
How can i achieve that?
What's your definition of a word? Anything between commas?
First get the words:
var words = mystring.Split(',');
Then add the apostrophes:
words = words.Select(w => String.Format("'{0}'", w));
And turn them back into one string:
var mynewstring = String.Join(",", words);
mystring = "'" + mystring.replace(",", "','") + "'";
I would let each "word" be determined by the regex \b word boundary. So, you have:
var output = Regex.Replace("A,B,C,D", #"(\b)", #"'$1");
string str = "a,b,c,d";
string.Format("'{0}'", str.Replace(",", "','"));
or
string str = "a,b,c,d";
StringBuilder sb = new StringBuilder(str.Length * 2 + 2);
foreach (var c in str.ToCharArray())
{
sb.AppendFormat((c == ',' ? "{0}" : "'{0}'"), c);
}
str = sb.ToString();
string mystring = "A,B,C,D";
string[] array = mystring.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string newstring = "";
foreach (var item in array)
{
newstring += "'" + item + "',";
}
newstring = newstring.Remove(newstring.Length - 1);
Console.WriteLine(newstring);
Output will be;
'A','B','C','D'
Here a DEMO.
Or more simple;
string mystring = "A,B,C,D";
Console.WriteLine(string.Format("'{0}'", mystring.Replace(",", "','")));
you can use regular expressions to solve this problem
like this:
string words= "A,B,C,D";Regex reg = new Regex(#"(\w+)");words = reg.Replace(words, match=> { return string.Format("'{0}'", match.Groups[1].Value); });

How do I use the Aggregate function to take a list of strings and output a single string separated by a space?

Here is the source code for this test:
var tags = new List<string> {"Portland", "Code","StackExcahnge" };
const string separator = " ";
tagString = tags.Aggregate(t => , separator);
Console.WriteLine(tagString);
// Expecting to see "Portland Code StackExchange"
Console.ReadKey();
Update
Here is the solution I am now using:
var tagString = string.Join(separator, tags.ToArray());
Turns out string.Join does what I need.
For that you can just use string.Join.
string result = tags.Aggregate((acc, s) => acc + separator + s);
or simply
string result = string.Join(separator, tags);
String.Join Method may be?
This is what I use
public static string Join(this IEnumerable<string> strings, string seperator)
{
return string.Join(seperator, strings.ToArray());
}
And then it looks like this
tagString = tags.Join(" ")

Categories