翻转字符串方法集锦

1)最简单的方法
public string Reverse(string s)

{

    char[] c = s.ToCharArray();

    string result = String.Empty;

    for (int i = c.Length - 1; i > -1; i--)

        result += c[i];

    return result;

}

2)效率较高的方法
public string ReverseByArray(string s)

{

    char[] c = s.ToCharArray();

    Array.Reverse(c);

    return new string(c);

}

3)借助Stack,利用FILO特性
public string ReverseByStack(string s)

{

    Stack<string> stack = new Stack<string>();

    for (int i = 0; i < s.Length; i++)

        stack.Push(s.Substring(i, 1));

    string result = String.Empty;

    for (int i = 0; i < s.Length; i++)

        result += stack.Pop();

    return result;

}

4)通过迭代,比较好的方法
public string Reverse(string s, int length)

{

    if (length == 1)

        return s;

    else

        return Reverse(s.Substring(1, s.Length - 1), length - 1) + s[0].ToString();

}

5)

private string Reverse(string source)

{

    int length=source.Length;

    char[] c = new char[length];

    for (int i = 0; i < length; i++)

    {

        c[i] = source[length - 1 - i];

    }

    return new string(c);

}

你可能感兴趣的:(字符串)