简体   繁体   中英

What's the best way to merge strings?

Let's say I have a foreach-loop with strings like this:

String newStr='';
String str='a b c d e';
foreach(String strChar in str.split(' ')) {
  newStr+=strChar+',';
}

the result would be something like: a,b,c,d,e, but what I want is a,b,c,d,e without the last comma. I normally split the last comma out but this seems ugly and overweight. Is there any lightweight way to do this?

Additional to this question: Is there any easy solution to add an "and" to the constellation that the result is something like: a, b, c, d and e for user output?

ps: I know that I can use the replace-method in the example but this is not what I'm looking because in most cases you can't use it (for example when you build a sql string).

I would use string.Join :

string newStr = string.Join(",", str.Split(' '));

Alternatively, you could add the separator at the start of the body of the loop, but not on the first time round.

I'd suggest using StringBuilder if you want to keep doing this by hand though. In fact, with a StringBuilder you could just unconditionally append the separator, and then decrement the length at the end to trim that end.

You also wrote:

for example when you build a sql string

It's very rarely a good idea to build a SQL string like this. In particular, you should absolutely not use strings from user input here - use parameterized SQL instead. Building SQL is typically the domain of ORM code... in which case it's usually better to use an existing ORM than to roll your own :)

you're characterizing the problem as appending a comma after every string except the last. Consider characterizing it as prepending a comma before every string but the first. It's an easier problem.

As for your harder version there are several dozen solutions on my blog and in this question.

Eric Lippert's challenge "comma-quibbling", best answer?

string.Join may be your friend:

String str='a b c d e';
var newStr = string.Join(",", str.Split(' '));

Here's how you can do it where you have "and" before the last value.

var vals = str.Split(' ');
var ans = vals.Length == 1 ?
          str :
          string.Join(", ", vals.Take(vals.Length - 1))) + ", and " + vals.Last();
newStr = String.Join(",", str.split(' '));

您可以使用正则Regex并用逗号替换空格

string newst = Regex.Replace(input, " ", ",");

First, you should be using a StringBuilder for string manipulations of this sort. Second, it's just an if conditional on the insert.

System.Text.StringBuilder newStr = new System.Text.StringBuilder("");
string oldStr = "a b c d e";

foreach(string c in oldStr.Split(' ')) {
    if (newStr.Length > 0) newStr.Append(",");
    newStr.Append(c);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM