
[英]In c#, how to combine strings and their frequency to a resulting string?
[英]Proper way in C# to combine an arbitrary number of strings into a single string
我轻松浏览了string
类的文档,并没有看到任何用于将任意数量的字符串组合成单个字符串的好工具。 我可以在我的程序中提出的最佳程序是
string [] assetUrlPieces = { Server.MapPath("~/assets/"),
"organizationName/",
"categoryName/",
(Guid.NewGuid().ToString() + "/"),
(Path.GetFileNameWithoutExtension(file.FileName) + "/")
};
string assetUrl = combinedString(assetUrlPieces);
private string combinedString ( string [] pieces )
{
string alltogether = "";
foreach (string thispiece in pieces) alltogether += alltogether + thispiece;
return alltogether;
}
但这似乎是太多的代码和太多的低效率(来自字符串添加)和尴尬。
如果要在值之间插入分隔符, string.Join
是您的朋友。 如果你只想连接字符串,那么你可以使用string.Concat
:
string assetUrl = string.Concat(assetUrlPieces);
这比使用空分隔符调用string.Join
稍微简单(并且可能更有效,但可能微不足道)。
如注释中所述,如果您实际在代码中的同一点构建数组,并且您不需要该数组用于其他任何内容,则只需直接使用连接:
string assetUrl = Server.MapPath("~/assets/") +
"organizationName/" +
"categoryName/" +
Guid.NewGuid() + "/" +
Path.GetFileNameWithoutExtension(file.FileName) + "/";
...或者可能使用string.Format
。
我想你想要一个StringBuilder
。
var sb = new StringBuilder(pieces.Count());
foreach(var s in pieces) {
sb.Append(s);
}
return sb.ToString();
更新
@FiredFromAmazon.com:我想你会想要使用其他人提供的string.Concat
解决方案
FillStringChecked
,它使用指针副本,而string.Join
使用StringBuilder
。 请参阅http://referencesource.microsoft.com/#mscorlib/system/string.cs,1512 。 (谢谢@Bas)。 string.Concat
是你想要的最合适的方法。
var result = string.Concat(pieces);
除非你想在各个字符串之间放置分隔符。 然后你会使用string.Join
var result = string.Join(",", pieces); // comma delimited result.
使用常规for循环执行此操作的简单方法:(因为您可以使用索引,加上我喜欢这些循环比foreach循环更好)
private string combinedString(string[] pieces)
{
string alltogether = "";
for (int index = 0; index <= pieces.Length - 1; index++) {
if (index != pieces.Length - 1) {
alltogether += string.Format("{0}/" pieces[index]);
}
}
return alltogether;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.