扭转一个字符串的最佳方法字符串、方法

2023-09-10 22:21:48 作者:浪荡街痞

我刚刚写一个字符串反向函数在C#2.0(即LINQ不可用),并提出了这一点:

 公共字符串反转(文本字符串)
{
    的char [] =的cArray text.ToCharArray();
    串反向=的String.Empty;
    的for(int i = cArray.Length  -  1; I> -1;我 - )
    {
        反向+ =的cArray [I]
    }
    返回反向;
}
 

我个人不是疯了有关功能,我相信,有一个更好的方式来做到这一点。有没有?

解决方案

 公共静态字符串反转(字符串s)
{
    的char [] charArray = s.ToCharArray();
    Array.Reverse(charArray);
    返回新的字符串(charArray);
}
 

我觉得上面的作品没有经过测试,虽然StringBuilder类也可以具有反转功能我还没有检查,虽然。

excel怎么将单元格中字符串按大小排序 最好是公式

I've just had to write a string reverse function in C# 2.0 (i.e. LINQ not available) and came up with this:

public string Reverse(string text)
{
    char[] cArray = text.ToCharArray();
    string reverse = String.Empty;
    for (int i = cArray.Length - 1; i > -1; i--)
    {
        reverse += cArray[i];
    }
    return reverse;
}

Personally I'm not crazy about the function and am convinced that there's a better way to do it. Is there?

解决方案

public static string Reverse( string s )
{
    char[] charArray = s.ToCharArray();
    Array.Reverse( charArray );
    return new string( charArray );
}

I think the above works not tested, although the stringbuilder class may also have a reverse function I haven't checked that though.