TechBrkTru
TechBrkTru

Reputation: 356

How to add a symbol character in the middle of string but not in the beginning or in the end of the string in C#

I have a string array of a dynamic size.

For example:

string[] UserName_arr = new string[usercount + 1]; 
// here usercount would be int value considering it as 4 so the array size would be 5.

I need to add every UserName_arr values into a single string merging with just a special character < symbol.

When I use this code main_UserName = String.Join("<", UserName_arr);

I get the string as main_UserName =a1<a2<a3< I don't need the < in the end of my string

I checked out this link but was not able to reach anywhere

Upvotes: 4

Views: 564

Answers (2)

Rohit Vipin Mathews
Rohit Vipin Mathews

Reputation: 11787

Would this be what you trying to do?

UserName_arr.Aggregate((x,y) => x + "<" + y);

You can check out more on Aggregate here.

Or you can do TrimEnd in your code :

main_UserName = String.Join("<", UserName_arr);
main_UserName = main_UserName.TrimEnd('<');

String.Join example :

string[] dinosaurs = new string[] { "Aeolosaurus",
        "Deinonychus", "Jaxartosaurus", "Segnosaurus" };        
string joinedString = string.Join(", ", dinosaurs);
Console.WriteLine(joinedString);

Output :

Aeolosaurus, Deinonychus, Jaxartosaurus, Segnosaurus

See there is no , in the end.

See String.Join this example.

Edit :

Based on OP's comment and Vera rind's comments the problem OP faced was the wrong declaration of String array. It had one element more than required, which resulted in being a Null element in the end of the array. This array when used with String.Join due to the null last element resulted in an unwanted "<" at the end.

Either change your array declaration to :

string[] UserName_arr = new string[usercount]; 

Or check for null string in the Join condition :

String.Join("<", UserName_arr.Where(x => string.IsNullOrEmpty(x) == false))

Upvotes: 5

user2160375
user2160375

Reputation:

Like 'Vera rind' mentioned in comment, you can just omit the empty user names in your array:

main_UserName = String.Join(
                         "<", 
                         UserName_arr.Where(name => !string.IsNullOrWhiteSpace(name));

The problem is that last element in your array is null or empty - that is way last comma is added after that there is nothing.

Upvotes: 3

Related Questions