简体   繁体   中英

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.

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")

Yes that seems to be ok.

About StringBuilder:
No need to use StringBuilder unless there are usually more than 4-5 elements after the split. 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.

You can also use String.Join() to put a delimited string array back together.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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