简体   繁体   English

如何在字符串中间添加符号字符,但不在C#中字符串的开头或结尾添加

[英]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. 我需要将每个UserName_arr值添加到一个字符串中,只与一个特殊字符< symbol合并。

When I use this code main_UserName = String.Join("<", UserName_arr); 当我使用此代码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 我得到的字符串为main_UserName =a1<a2<a3<我不需要<在我的字符串的末尾

I checked out this link but was not able to reach anywhere 我检查了这个链接,但无法到达任何地方

Would this be what you trying to do? 这会是你想要做的吗?

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

You can check out more on Aggregate here . 您可以在此处查看有关Aggregate的更多信息

Or you can do TrimEnd in your code : 或者您可以在代码中执行TrimEnd

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

String.Join example : String.Join示例:

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

Output : 输出:

Aeolosaurus, Deinonychus, Jaxartosaurus, Segnosaurus Aeolosaurus,Deinonychus,Jaxartosaurus,Segnosaurus

See there is no , in the end. 看有没有到底。

See String.Join this example . 请参见String.Join 此示例

Edit : 编辑:

Based on OP's comment and Vera rind's comments the problem OP faced was the wrong declaration of String array. 根据OP的评论和Vera rind的评论,OP面临的问题是String数组的错误声明。 It had one element more than required, which resulted in being a Null element in the end of the array. 它有一个元素超过了需要,导致在数组末尾是一个Null元素。 This array when used with String.Join due to the null last element resulted in an unwanted "<" at the end. 由于null last元素与String.Join一起使用时,此数组在String.Join导致不需要的“<”。

Either change your array declaration to : 将数组声明更改为:

string[] UserName_arr = new string[usercount]; 

Or check for null string in the Join condition : 或者在Join条件中检查空字符串:

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

Like 'Vera rind' mentioned in comment, you can just omit the empty user names in your array: 与评论中提到的'Vera rind'一样,您可以省略数组中的空用户名:

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. 问题是数组中的最后一个元素为null或为空 - 这就是在没有任何内容之后添加最后一个逗号的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM