1

Code:

string testquestions = "1,2,100,3,4,101,98,99";
string[] qidarray = testquestions.Split(',');

StringBuilder sb = new StringBuilder();

foreach (string s in qidarray)
{
    sb.Append(String.Format(@"({0}),",s));
}

string output= sb.ToString().Substring(0, sb.ToString().Length - 1);

Desired output =

(1),(2),(100),(3),(4),(101),(98),(99)

The code works. I want to know is this the best way for achieving the result. Is there a better way to achieve the desired result?

Is there a way not to use a foreach loop?

2
  • 1
    Use String.Join() Commented Jun 14, 2018 at 17:43
  • 4
    This should be more appropriate for code review. Commented Jun 14, 2018 at 17:50

2 Answers 2

8

This would do the trick. The code is first splitting the string and using linq, formatting to desired output.

var strToPrint = string.Join(",", testquestions.Split(',')
                       .Select(s => string.Format(@"({0})", s)));

Console Output

Console.WriteLine(string.Join(",", testquestions.Split(',')
                        .Select(s => string.Format(@"({0})", s))));

You can check the live fiddle here - https://dotnetfiddle.net/4zBqMf

Edit :

As suggested by @paparazzo, you can use string interpolation to write the syntax as

var strToPrint = string.Join(",", testquestions.Split(',').Select(s => $"({s})"));

Live fiddle - https://dotnetfiddle.net/xppLH2

Sign up to request clarification or add additional context in comments.

5 Comments

fantastic. it worked. just one line of code. This is what I was looking for,
$"({s})" is maybe cleaner.
@paparazzo - Agreed. Added in my answer.
@user1672994 you should use the real name: "string interpolation" rather than "string format short notation"
@maccettura - Done.
1

Here are some other ways using Replace.

string testquestions = "1,2,100,3,4,101,98,99";

string result = new StringBuilder("(" + testquestions + ")").Replace(",", "),(").ToString();

string result1 = "(" + testquestions.Replace(",", "),(") + ")";

string result2 = "(" + new Regex(",").Replace(testquestions, "),(") + ")";

1 Comment

perfect and simple

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.