Build a string from a string[] without using any loops - c#

I have a string array. It is dynamic and can be of any length(0 also). How can I make a single string from the array, delimited by any separator like ; or | ??
string str = string.empty;
string[] arrOptions = strOptions.Split(new string[]{"\n"}, StringSplitOptions.RemoveEmptyEntries);
Now, have to make the string from arrOptions and put it in str

Use string.Join:
string result = string.Join("\n", arrOptions);
Or simply concat them, if you don't need the separator anymore:
string result = string.Concat(arrOptions);

Use String.Join(separator, objects) method.

You can try both way:
string[] strArr = { "Abc", "DEF", "GHI" };
// int i = 0;
// string final=string.Empty;
//IterationStart:
// if (i < strArr.Length)
// {
// final += strArr[i] + ",";
// i++;
// goto IterationStart;
// }
//Console.WriteLine(final);
string str = string.Join(",", strArr);
Console.WriteLine(str);

str = string.Join( ';', arrOptions );

Try : string.Join(seperator, arrOptions);

You might be looking for the below solution.
string str = string.empty;
string[] arrOptions = strOptions.Split(new string[]{"\n"}, StringSplitOptions.RemoveEmptyEntries);
str = string.Concat(arrOptions);
Thanks,
Praveen

Related

Best way to add delimeter betwen text in an array?

How can i add a symbol between the array of strings in this method? I tried using an if statement within the for each loop that added the symbol between each index of the array but it didn't work.
public string addSymbolBetweenStringArray(string[] strArray, string symbol)
{
string s = default(string);
foreach (string str in strArray)
{
}
return s;
}
string[] strArray = { "Hello", "World", };
string symbol = "-";
addSymbolBetweenStringArray(stringArray, symbol);
The method then returns Hello-World
You are looking for the string.Join method. For example:
string[] strArray = { "Hello", "World", };
string symbol = "-";
var output = string.Join(symbol, strArray);
You can use String.Join:
string result = String.Join(symbol, strArray);

how to split comma with double quotes in c#?

string strExample =
"\"10553210\",\"na\",\"398,633,000\",\"20130709\",\"20130502\",\"20120724\",";
how to split above string with ","
I need an answer like
string[] arrExample = YourFunc(strExample);
arrExample[0] == "10553210";
arrExample[1] == "na";
arrExample[2] == "398,633,000";
...
with split option.
thanks in advance
Here is an easy way,
using Microsoft.VisualBasic.FileIO;
IList<string> arrExample;
using(var csvParser = new TextFieldParser(new StringReader(strExample))
{
fields = csvParser.ReadFields();
}
You may split not by comma "," but by whole string "\",\"".
Do not forget to Trim leading and trailing quotations ":
String strExample =
"\"10553210\",\"na\",\"398,633,000\",\"20130709\",\"20130502\",\"20120724\"";
string[] arrExample = St.Trim('"').Split(new String[] {"\",\""}, StringSplitOptions.None);
You can split on "," , The first and last entry you have to clean the " in the last and first entry:
string[] arr = strExample .Split(new string[] { "\",\"" },
StringSplitOptions.None);
//remove the extra quotes from the last and the first entry
arr[0] = arr[0].SubString(1,arr[0].Length - 1);
int last = arr.Length - 1;
arr[last] = arr[last].SubString(0,arr[last].Length - 1);
string[] arrExample = strExample.Split(",");
would do it, but your code won't compile. I assume you meant:
string strExample = "10553210,na,398,633,000,20130709,20130502,20120724";
If this isn't what you meant, please correct the question.
Assuming you meant this:
string strExample = "\"10553210\",\"na\",\"398,633,000\",\"20130709\",\"20130502\",\"20120724\"";
Split then Select the substring:
string[] parts = strExample.Split(',').Select(x => x.Substring(1, x.Length - 2)).ToArray();
Result:
strExample.Split(',');
You need to escape the double quotes if they're meant to be contained in your example string.
Using the example from Jodrell
private string[] SplitFields(string csvValue)
{
//if there aren't quotes, use the faster function
if (!csvValue.Contains('\"') && !csvValue.Contains('\''))
{
return csvValue.Trim(',').Split(',');
}
else
{
//there are quotes, use this built in text parser
using(var csvParser = new Microsoft.VisualBasic.FileIO.TextFieldParser(new StringReader(csvValue.Trim(','))))
{
csvParser.Delimiters = new string[] { "," };
csvParser.HasFieldsEnclosedInQuotes = true;
return csvParser.ReadFields();
}
}
}
This worked for me
public static IEnumerable<string> SplitCSV(string strInput)
{
string[] str = strInput.Split(',');
if (str == null)
yield return null;
StringBuilder quoteS = null;
foreach (string s in str)
{
if (s.StartsWith("\""))
{
if (s.EndsWith("\""))
{
yield return s;
}
quoteS = new StringBuilder(s);
continue;
}
if (quoteS != null)
{
quoteS.Append($",{s}");
if (s.EndsWith("\""))
{
string s1 = quoteS.ToString();
quoteS = null;
yield return s1;
}
else
continue;
}
yield return s;
}
}
static void Main(string[] args)
{
string s = "111,222,\"33,44,55\",666,\"77,88\",\"99\"";
Console.WriteLine(s);
var sp = SplitCSV(s);
foreach (string s1 in sp)
{
Console.WriteLine(s1);
}
Console.ReadKey();
}
you can do that by doing this ..
string stringname= "10553210,na,398,633,000,20130709,20130502,20120724";
List<String> asd = stringname.Split(',');
or if you wanr array then
array[] asd = stringname.Split(',').ToArray;

Splitting by string with a separator with more than one char

Suppose i have a string separator eg "~#" and have a string like "leftSide~#righside"
How do you get you leftside and rightside without separator?
string myLeft=?;
string myRight=?
How do you do it?
thanks
string[] splitResults = myString.Split(new [] {"~#"}, StringSplitOptions.None);
And if you want to make sure you get at most 2 substrings (left and right), use:
int maxResults = 2;
string[] splitResults =
myString.Split(new [] {"~#"}, maxResults, StringSplitOptions.None)
string[] strs =
string.Split(new string[] { "~#" }, StringSplitOptions.RemoveEmptyEntries);
use String.Split
string str = "leftSide~#righside";
str.Split(new [] {"~#"}, StringSplitOptions.None);
the split function has an overload that accepts an array of strings instead of chars...
string s = "leftSide~#righside";
string[] ss = s.Split(new string[] {"~#"}, StringSplitOptions.None);
var s = "leftSide~#righside";
var split = s.Split (new string [] { "~#" }, StringSplitOptions.None);
var myLeft = split [0];
var myRight = split [1];
String myLeft = value.Substring(0, value.IndexOf(seperator));
String myRight = value.Substring(value.IndexOf(seperator) + 1);

builtin function for string value

strvalues=#"Emp_Name;Emp_ID;23;24;25;26";
contains values like this
taking the above string as an input the output should be like this
string strresult=#"23;24;25;26";
is there any built in function to do like this
thnaks
prince
Let's add a LINQ solution to the lot...
string result = String.Join(";", values.Split(';').Skip(2).ToArray());
Or another possibility
string result = values.Split(new char[] { ';' }, 3)[2];
Both work, but I wouldn't call them elegant either.
string[] values = strvalues.Split(new char[] { ';' });
values will be a string array containing the first column in values[0], second in values[1], etc.
You can use it like this:
for (int i = 2, i < values.Length, i++) {
Console.WriteLine(values[i]);
}
Regex class?
var strresult = new Regex("([0-9]+;?)*").Match(strvalues).Value;
string strresult = strvalues.Replace("Emp_Name;Emp_ID;", "");
How about...
string result = String.Join(";", strvalues.Split(';'), 2, 4);

remove last word in label split by \

Ok i have a string where i want to remove the last word split by \
for example:
string name ="kak\kdk\dd\ddew\cxz\"
now i want to remove the last word so that i get a new value for name as
name= "kak\kdk\dd\ddew\"
is there an easy way to do this
thanks
How do you get this string in the first place? I assume you know that '' is the escape character in C#. However, you should get far by using
name = name.TrimEnd('\\').Remove(name.LastIndexOf('\\') + 1);
string result = string.Join("\\",
"kak\\kdk\\dd\\ddew\\cxz\\"
.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries)
.Reverse()
.Skip(1)
.Reverse()
.ToArray()) + "\\";
Here's a non-regex manner of doing it.
string newstring = name.SubString(0, name.SubString(0, name.length - 1).LastIndexOf('\\'));
This regex replacement should do the trick:
name = Regex.Replace(name, #"\\[a-z]*\\$", "\\");
Try this:
const string separator = "\\";
string name = #"kak\kdk\dd\ddew\cxz\";
string[] names = name.Split(separator.ToCharArray(),
StringSplitOptions.RemoveEmptyEntries);
string result = String.Join(separator, names, 0, names.Length - 1) + separator;
EDIT:I just noticed that name.Substring(0,x) is equivalent to name.Remove(x), so I've changed my answer to reflect that.
In a single line:
name = name = name.Remove(name.Remove(name.Length - 1).LastIndexOf('\\') + 1);
If you want to understand it, here's how it might be written out (overly) verbosely:
string nameWithoutLastSlash = name.Remove(name.Length - 1);
int positionOfNewLastSlash = nameWithoutLastSlash.LastIndexOf('\\') + 1;
string desiredSubstringOfName = name.Remove(positionOfNewLastSlash);
name = desiredSubstringOfName;
My Solution
public static string RemoveLastWords(this string input, int numberOfLastWordsToBeRemoved, char delimitter)
{
string[] words = input.Split(new[] { delimitter });
words = words.Reverse().ToArray();
words = words.Skip(numberOfLastWordsToBeRemoved).ToArray();
words = words.Reverse().ToArray();
string output = String.Join(delimitter.ToString(), words);
return output;
}
Function call
RemoveLastWords("kak\kdk\dd\ddew\cxz\", 1, '\')
string name ="kak\kdk\dd\ddew\cxz\"
string newstr = name.TrimEnd(#"\")
if you working with paths:
string name = #"kak\kdk\dd\ddew\cxz\";
Path.GetDirectoryName(name.TrimEnd('\\'));
//ouput: kak\kdk\dd\ddew
string[] temp = name.Split('\\');
string last = "\\" + temp.Last();
string target = name.Replace(last, "");
For Linq-lovers: With later C# versions you can use SkipLast together with Split and string.Join:
var input = #"kak\kdk\dd\ddew\cxz\";
string result = string.Join( #"\", input
.Split( #"\", StringSplitOptions.RemoveEmptyEntries )
.SkipLast( 1 ))
+ #"\";

Categories