String.join array from last element - c#

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());
}

Related

Convert from 'string' to 'System.Collections.Generic.IEnumerable<string>

Here is my code :
var query = System.IO.File.ReadLines(#"c:\temp\mytext.txt")
.Select(line => line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)[0]);
System.IO.File.WriteAllLines(#"c:\temp\WriteLines.txt", query);
I want to convert quert to string so I can edit it , like this code for example
string[] res = s.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
I can use res[0].Substring and res[0].PadRight many options in text
So how can I convert my first code to become string but do same function?
I'm assuming that your file looks like this (Like grid):
Text11 Text12 Text13 Text14
Text21 Text22 Text23 Text24
Text31 Text32 Text33 Text34
Now you want to split it by cells so:
var query = System.IO.File.ReadLines(#"c:\temp\mytext.txt")
.Select(line => line.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries)).ToList();
Now when you writing this back to the file you should join the lines:
System.IO.File.WriteAllLines(#"c:\temp\WriteLines.txt", query.Select(line => String.Join(" ", line)));
And when you want to edit cell you can use:
query[row][column].Substring();
You can simply add .ToArray() at the end :
var query = System.IO.File.ReadLines(#"c:\temp\mytext.txt")
.Select(line => line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)[0])
.ToArray();
So you can do like query[0].Substring and query[0].PadRight.
Is that what you want?

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); });

formatting string in C#

How can I convert this list of strings to comma separated value enclosed within quotes without any escape characters?
{"apple", "berry", "cherry"} => well, ""apple", "berry", "cherry""
If I understood you correctly,
"\"" + String.Join("\", \"", new string[]{"apple","berry","cherry"}) + "\"";
or, alternatively,
String.Format("\"{0}\"", String.Join("\", \"", new string[] {"apple","berry","cherry"}));
Read more on System.String.Join(...).
Hope this will do the job
var ar = new []{ "apple", "berry", "cherry" };
var separator = "\",\"";
var enclosingTag = "\"";
Console.WriteLine ( enclosingTag + String.Join(separator, ar) + enclosingTag );
If you are using C#:
using System;
string[] arr = new string[] { "apple", "berry", "cherry" };
string sep = "\",\"";
string enclosure = "\"";
string result = enclosure + String.Join(sep, arr) + enclosure;

convert string array to string

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];

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