简体   繁体   English

在C#中反转字符串的最佳方法

[英]Best way to reverse string in c#

Is this the right method to reverse a string? 这是反转字符串的正确方法吗? I'm planning to use it to reverse a string like: Products » X1 » X3 to X3 « X1 « Products I want it to be a global function which can be used elsewhere. 我打算用它来反转一个字符串,例如:产品»X1»X3到X3«X1«产品我希望它成为可以在其他地方使用的全局函数。

public static string ReverseString(string input, string separator, string outSeparator)
{
    string result = String.Empty;
    string[] temp = Regex.Split(input, separator, RegexOptions.IgnoreCase);
    Array.Reverse(temp);
    for (int i = 0; i < temp.Length; i++)
    {
        result += temp[i] + " " + outSeparator + " ";
    }
    return result;
}

How about: 怎么样:

String.Join(" « ", "Products » X1 » X3".Split(new[]{" » "}, 
    StringSplitOptions.None).Reverse().ToArray());

EDIT: The updated version version will work if the components contain spaces (eg "Foo Products » X1 » X3") 编辑:如果组件包含空格(例如,“ Foo Products»X1»X3”),则更新的版本将可用

Yes that seems to be ok. 是的,这似乎还可以。

About StringBuilder: 关于StringBuilder:
No need to use StringBuilder unless there are usually more than 4-5 elements after the split. 除非拆分后通常有4-5个以上的元素,否则无需使用StringBuilder。 If there are usually less than that then aggregation is fine. 如果通常少于该数量,那么聚合就可以了。

You should use a StringBuilder rather than just string aggregation, especially if this is going to be used a lot. 您应该使用StringBuilder而不是仅使用字符串聚合,尤其是在要大量使用的情况下。

You can also use String.Join() to put a delimited string array back together. 您还可以使用String.Join()将定界的字符串数组放回原处。

I used the following: 我使用了以下内容:

  /// <summary>
    /// From BReusable
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="items"></param>
    /// <param name="toStringFunc"></param>
    /// <param name="seperator"></param>
    /// <returns></returns>
    public static string ToJoinedString<T>(this IList<T> items, Func<int, T, string> toStringFunc, string seperator)
    {

        var sb = new StringBuilder();

        for (int i = 0; i < items.Count(); i++)
        {
            sb.Append((i != 0 ? seperator : String.Empty) + toStringFunc(i,items[i]));

        }
        return sb.ToString();
    }

    public static string ToStringFromCharArray(this IEnumerable<char> items)
    {
        return items.ToJoinedString(x => x.ToString(), string.Empty);
    }

with stringValue.Reverse().ToStringFromCharArray(); stringValue.Reverse().ToStringFromCharArray();

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

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