3

I want to convert Array into string as

string[] parts={"1","2","3","4"};

and output as

string str="%1%2%3%4%";
7
  • 2
    string.Join("%", parts) then add in the start and end %. Commented Oct 28, 2015 at 11:28
  • I think you may have googled this as well. Commented Oct 28, 2015 at 11:30
  • 1
    Linq: parts.Aggregate("%", (current, next) => current + next + "%") Commented Oct 28, 2015 at 11:35
  • @Klaudiuszbryjamus While clever this suffers from the concatenating strings in a loop problem. Commented Oct 28, 2015 at 12:45
  • @juharr But this is simple linq query not in loop so you can use linq Commented Oct 28, 2015 at 14:56

4 Answers 4

3

Use string.Join:

var str = string.Join("%", parts);

And add in the surrounding % marks:

str = string.format("%{0}%", str);
Sign up to request clarification or add additional context in comments.

Comments

2

Using C#-6 string interpolation:

var str = $"%{string.Join("%", parts)}%";

1 Comment

Probably worth mentioning this will only work in C#6.
1

string.Join will concatenate the strings in the array with a delimiter. Then you just have to add the "%" to the beginning and end.

string str = "%" + string.Join("%", parts) + "%";

1 Comment

:- thanks its working Properly
0
    StringBuilder builder = new StringBuilder();    
    foreach(string tmp in parts)
    {
       builder.append("%");
       builder.append(tmp);
    }
    builder.append("%");
    string result = builder.ToString();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.