我刚刚在c# 2.0中写了一个字符串反向函数(即LINQ不可用),然后想到了这个:

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;
}

就我个人而言,我并不喜欢这个功能,我相信有更好的方法来实现它。是吗?


当前回答

选择倒档(“somestring”); 完成了。

其他回答

使用LINQ的聚合函数

string s = "Karthik U";
s = s.Aggregate(new StringBuilder(), (o, p) => o.Insert(0, p)).ToString();

处理所有类型的unicode字符

使用System.Globalization;

    public static string ReverseString(this string content) {

        var textElementEnumerator = StringInfo.GetTextElementEnumerator(content);

        var SbBuilder = new StringBuilder(content.Length);

        while (textElementEnumerator.MoveNext()) {
            SbBuilder.Insert(0, textElementEnumerator.GetTextElement());
        }

        return SbBuilder.ToString();
    }

我们可以使用两个指针,一个指向字符串的开始,另一个指向字符串的结束。然后每次交换第i个和第j个指针的值,第i个指针的值递增+1,第j个指针的值递减-1。

string s = Console.ReadLine();
Console.WriteLine(s + "\n");
char[] charArray = s.ToCharArray();
int i = 0, j = s.Length - 1;
while (i < j) {
    char temp = charArray[i];
    charArray[i] = charArray[j];
    charArray[j] = temp;
    i++; j--;
}
string ans = new string(charArray);
Console.WriteLine(ans + "\n");
// Input: hello
// Output: olleh
    string original = "Stack Overflow";
    string reversed = new string(original.Reverse().ToArray());

如果字符串包含Unicode数据(严格地说,非bmp字符),其他已经发布的方法将破坏它,因为在反转字符串时不能交换高和低代理代码单元的顺序。(关于这方面的更多信息可以在我的博客上找到。)

下面的代码示例将正确地反转包含非bmp字符的字符串,例如,“\U00010380\U00010381”(ugartic Letter Alpa, ugartic Letter Beta)。

public static string Reverse(this string input)
{
    if (input == null)
        throw new ArgumentNullException("input");

    // allocate a buffer to hold the output
    char[] output = new char[input.Length];
    for (int outputIndex = 0, inputIndex = input.Length - 1; outputIndex < input.Length; outputIndex++, inputIndex--)
    {
        // check for surrogate pair
        if (input[inputIndex] >= 0xDC00 && input[inputIndex] <= 0xDFFF &&
            inputIndex > 0 && input[inputIndex - 1] >= 0xD800 && input[inputIndex - 1] <= 0xDBFF)
        {
            // preserve the order of the surrogate pair code units
            output[outputIndex + 1] = input[inputIndex];
            output[outputIndex] = input[inputIndex - 1];
            outputIndex++;
            inputIndex--;
        }
        else
        {
            output[outputIndex] = input[inputIndex];
        }
    }

    return new string(output);
}