2

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?

p.s.: 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).

4

7 回答 7

11

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 :)

于 2013-02-14T14:01:25.090 回答
4

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?

于 2013-02-14T15:12:13.183 回答
2

string.Join may be your friend:

String str='a b c d e';
var newStr = string.Join(",", str.Split(' '));
于 2013-02-14T14:01:57.673 回答
2

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();
于 2013-02-14T14:05:41.380 回答
1
newStr = String.Join(",", str.split(' '));
于 2013-02-14T14:02:19.827 回答
1

You can use Regex and replace whitespaces with commas

string newst = Regex.Replace(input, " ", ",");
于 2013-02-14T14:04:38.177 回答
0

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);
}
于 2013-02-14T14:02:51.787 回答