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

ssilas777
  • 9,672
  • 4
  • 45
  • 68
Jan Hommes
  • 5,122
  • 4
  • 33
  • 45

7 Answers7

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • What is ORM? Object Role Modeling? – Jan Hommes Feb 14 '13 at 14:09
  • I'am using LINQ. Is this a ORM? – Jan Hommes Feb 14 '13 at 14:16
  • @JanHommes: Yes. (Or rather, LINQ comes in several different flavours, but most of the db-related ones would count as ORMs.) If you're using LINQ, why would you be creating a SQL statement yourself at all? – Jon Skeet Feb 14 '13 at 14:23
  • To do a fulltext search on a dynamical created grid. It's not SQL, but SQL-Like with dynamic-LINQ. Is there any better solution for a fulltext search? – Jan Hommes Feb 14 '13 at 14:28
  • @JanHommes: We'd need to know more about *exactly* what you were doing... but in general you shouldn't need to include values in strings for queries. It's fraught with problems. – Jon Skeet Feb 14 '13 at 14:29
  • thx for your help. Join and Stringbuilder helped me and I will review my concept. – Jan Hommes Feb 14 '13 at 14:34
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?

Community
  • 1
  • 1
Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
2

string.Join may be your friend:

String str='a b c d e';
var newStr = string.Join(",", str.Split(' '));
Daniel Kelley
  • 7,579
  • 6
  • 42
  • 50
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();
juharr
  • 31,741
  • 4
  • 58
  • 93
1
newStr = String.Join(",", str.split(' '));
PhonicUK
  • 13,486
  • 4
  • 43
  • 62
1

You can use Regex and replace whitespaces with commas

string newst = Regex.Replace(input, " ", ",");
VladL
  • 12,769
  • 10
  • 63
  • 83
  • 1
    Why bother with `Regex.Replace` when there's `string.Replace` and the expression is so simple? – juharr Feb 14 '13 at 14:13
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);
}
Joel Etherton
  • 37,325
  • 10
  • 89
  • 104