问题
What I'd prefer is something like:
string[] strArray = {"Hi", "how", "are", "you"};
string strNew = strArray.Delimit(chDelimiter);
However, there is no such function. I've looked over MSDN and nothing looked to me as a function that would perform the same action. I looked at StringBuilder, and again, nothing stood out to me. Does anyone know of a not to extremely complicated one liner to make an array a delimited string. Thanks for your guys' help.
UPDATE: Wow, lol, my bad. I kept looking at the .Join on the array itself and it was bugging the hell out of me. I didn't even look at String.Join. Thanks guys. Once it allows me to accept I shall. Preciate the help.
回答1:
For arrays, you can use:
string.Join(", ", strArray);
Personally, I use an extension method that I can apply to enumerable collections of all types:
public static string Flatten(this IEnumerable elems, string separator)
{
if (elems == null)
{
return null;
}
StringBuilder sb = new StringBuilder();
foreach (object elem in elems)
{
if (sb.Length > 0)
{
sb.Append(separator);
}
sb.Append(elem);
}
return sb.ToString();
}
...Which I use like so:
strArray.Flatten(", ");
回答2:
You can use the static String.Join method:
String strNew = String.Join(chDelimiter, strArray);
EDIT: In response to comment:
Based on your comment, you can take several arrays, concatenate them together, and then join the entire resulting array. You can do this by using the IEnumerable extension method Concat
. Here's an example:
//define my two arrays...
string[] strArray = { "Hi", "how", "are", "you" };
string[] strArray2 = { "Hola", "como", "esta", "usted" };
//Concatenate the two arrays together (forming a third array) and then call join on it...
string strNew = String.Join(",", strArray.Concat(strArray2));
Hope this helps!
回答3:
Have a look at String.Join().
Your sample must look like this :
string delimiter = ","
string[] strArray = { "Hi", "how", "are", "you" };
string strNew = String.Join(delimiter, strArray);
回答4:
Use String.Join
string[] strArray = {"Hi", "how", "are", "you"};
string strNew = String.Join("," strArray);
回答5:
in this case, String.Join() is probably the easiest way to go, you can equally use LINQ though
var comSeparatedStrings = strings.Aggregate((acc, item) => acc + ", " + item);
来源:https://stackoverflow.com/questions/3558246/c-string-to-delimited-string-is-there-a-one-liner