C# 字符串中所有字母字符的大小写反转

发布于 2024-09-18 16:20:39 字数 728 浏览 7 评论 0原文

反转 C# 字符串中所有字母字符大小写的最简单方法是什么?例如“aBc1$;”应变为“AbC1$;”我可以轻松地编写一个方法来执行此操作,但我希望有一个我不知道的库调用会让这变得更容易。我还想避免列出所有已知的字母字符并将每个字符与列表中的字符进行比较。也许这可以用正则表达式来完成,但我不太了解它们。谢谢。

感谢您的帮助。我为此创建了一个字符串扩展方法,该方法主要受到 Anthony Pegram 解决方案的启发,但没有 LINQ。我认为这在可读性和性能之间取得了很好的平衡。这是我想出的。

public static string SwapCase(this string source) {
    char[] caseSwappedChars = new char[source.Length];
    for(int i = 0; i < caseSwappedChars.Length; i++) {
        char c = source[i];
        if(char.IsLetter(c)) {
            caseSwappedChars[i] =
                char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
        } else {
            caseSwappedChars[i] = c;
        }
    }
    return new string(caseSwappedChars);
}

What is the simplest way to reverse the case of all alphabetic characters in a C# string? For example "aBc1$;" should become "AbC1$;" I could easily write a method that does this, but I am hoping there is a library call that I don't know about that would make this easier. I would also like to avoid having a list of all known alphabetic characters and comparing each character to what is in the list. Maybe this can be done with regular expressions, but I don't know them very well. Thanks.

Thanks for the help. I created a string extension method for this that is mostly inspired by Anthony Pegram's solution, but without the LINQ. I think this strikes a good balance between readability and performance. Here is what I came up with.

public static string SwapCase(this string source) {
    char[] caseSwappedChars = new char[source.Length];
    for(int i = 0; i < caseSwappedChars.Length; i++) {
        char c = source[i];
        if(char.IsLetter(c)) {
            caseSwappedChars[i] =
                char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
        } else {
            caseSwappedChars[i] = c;
        }
    }
    return new string(caseSwappedChars);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

无戏配角 2024-09-25 16:20:39

您可以使用 LINQ 来完成此操作。一种方法:

string input = "aBc1$";
string reversedCase = new string(
    input.Select(c => char.IsLetter(c) ? (char.IsUpper(c) ?
                      char.ToLower(c) : char.ToUpper(c)) : c).ToArray());

You could do it in a line with LINQ. One method:

string input = "aBc1$";
string reversedCase = new string(
    input.Select(c => char.IsLetter(c) ? (char.IsUpper(c) ?
                      char.ToLower(c) : char.ToUpper(c)) : c).ToArray());
一江春梦 2024-09-25 16:20:39

如果您不关心国际化:

string input = "aBc1$@[\\]^_{|{~";
Encoding enc = new System.Text.ASCIIEncoding();
byte[] b = enc.GetBytes(input);
for (int i = input.Length - 1; i >= 0; i -= 1) {
   if ((b[i] & 0xdf) >= 65 && (b[i] & 0xdf) <= 90) { //check if alpha
      b[i] ^= 0x20; // then XOR the correct bit to change case
   }
}
Console.WriteLine(input);
Console.WriteLine(enc.GetString(b));

另一方面,如果您确实关心国际化,则需要将 CultureInfo.InvariantCulture 传递给 ToUpper() 和 ToLower() 函数。 ..

If you don't care about internationalization:

string input = "aBc1$@[\\]^_{|{~";
Encoding enc = new System.Text.ASCIIEncoding();
byte[] b = enc.GetBytes(input);
for (int i = input.Length - 1; i >= 0; i -= 1) {
   if ((b[i] & 0xdf) >= 65 && (b[i] & 0xdf) <= 90) { //check if alpha
      b[i] ^= 0x20; // then XOR the correct bit to change case
   }
}
Console.WriteLine(input);
Console.WriteLine(enc.GetString(b));

If, on the other hand, you DO care about internationalization, you'll want to pass in CultureInfo.InvariantCulture to your ToUpper() and ToLower() functions...

情定在深秋 2024-09-25 16:20:39

如果您不了解 LINQ,您可以采用老式方法。

static string InvertCasing(string s)
{
    char[] c = s.ToCharArray();
    char[] cUpper = s.ToUpper().ToCharArray();
    char[] cLower = s.ToLower().ToCharArray();

    for (int i = 0; i < c.Length; i++)
    {
        if (c[i] == cUpper[i])
        {
            c[i] = cLower[i];
        }
        else
        {
            c[i] = cUpper[i];
        }
    }

    return new string(c);
}

You could do it old-school if you don't know LINQ.

static string InvertCasing(string s)
{
    char[] c = s.ToCharArray();
    char[] cUpper = s.ToUpper().ToCharArray();
    char[] cLower = s.ToLower().ToCharArray();

    for (int i = 0; i < c.Length; i++)
    {
        if (c[i] == cUpper[i])
        {
            c[i] = cLower[i];
        }
        else
        {
            c[i] = cUpper[i];
        }
    }

    return new string(c);
}
凉墨 2024-09-25 16:20:39

以下是正则表达式方法:

string input = "aBcdefGhI123jKLMo$";
string result = Regex.Replace(input, "[a-zA-Z]",
                            m => Char.IsUpper(m.Value[0]) ?
                                 Char.ToLower(m.Value[0]).ToString() :
                                 Char.ToUpper(m.Value[0]).ToString());
Console.WriteLine("Original: " + input);
Console.WriteLine("Modified: " + result);

您可以使用 Char.Parse(m.Value) 作为 m.Value[0] 的替代方案。另外,请注意改用 ToUpperInvariantToLowerInvariant 方法。有关详细信息,请参阅此问题: 在 C# 中,什么是ToUpper() 和 ToUpperInvariant() 之间的区别?

Here's a regex approach:

string input = "aBcdefGhI123jKLMo$";
string result = Regex.Replace(input, "[a-zA-Z]",
                            m => Char.IsUpper(m.Value[0]) ?
                                 Char.ToLower(m.Value[0]).ToString() :
                                 Char.ToUpper(m.Value[0]).ToString());
Console.WriteLine("Original: " + input);
Console.WriteLine("Modified: " + result);

You can use Char.Parse(m.Value) as an alternate to m.Value[0]. Also, be mindful of using the ToUpperInvariant and ToLowerInvariant methods instead. For more info see this question: In C# what is the difference between ToUpper() and ToUpperInvariant()?

丿*梦醉红颜 2024-09-25 16:20:39

我为字符串创建了一个扩展方法,它就是这样做的!

public static class InvertStringExtension
{
    public static string Invert(this string s)
    {
        char[] chars = s.ToCharArray();
        for (int i = 0; i < chars.Length; i++)
            chars[i] = chars[i].Invert();

        return new string(chars);
    }
}

public static class InvertCharExtension
{
    public static char Invert(this char c)
    {
        if (!char.IsLetter(c))
            return c;

        return char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
    }
}

使用

var hello = "hELLO wORLD";
var helloInverted = hello.Invert();

// helloInverted == "Hello World"

I made an extension method for strings which does just this!

public static class InvertStringExtension
{
    public static string Invert(this string s)
    {
        char[] chars = s.ToCharArray();
        for (int i = 0; i < chars.Length; i++)
            chars[i] = chars[i].Invert();

        return new string(chars);
    }
}

public static class InvertCharExtension
{
    public static char Invert(this char c)
    {
        if (!char.IsLetter(c))
            return c;

        return char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
    }
}

To use

var hello = "hELLO wORLD";
var helloInverted = hello.Invert();

// helloInverted == "Hello World"
意犹 2024-09-25 16:20:39
        char[] carr = str.ToCharArray();
        for (int i = 0; i < carr.Length; i++)
        {
            if (char.IsLetter(carr[i]))
            {
                carr[i] = char.IsUpper(carr[i]) ? char.ToLower(carr[i]) : char.ToUpper(carr[i]);
            }
        }
        str = new string(carr);
        char[] carr = str.ToCharArray();
        for (int i = 0; i < carr.Length; i++)
        {
            if (char.IsLetter(carr[i]))
            {
                carr[i] = char.IsUpper(carr[i]) ? char.ToLower(carr[i]) : char.ToUpper(carr[i]);
            }
        }
        str = new string(carr);
走走停停 2024-09-25 16:20:39

昨天有人问我类似的问题,我的回答是:

public static partial class StringExtensions {
    public static String InvertCase(this String t) {
        Func<char, String> selector=
            c => (char.IsUpper(c)?char.ToLower(c):char.ToUpper(c)).ToString();

        return t.Select(selector).Aggregate(String.Concat);
    }
}

您可以轻松更改方法签名以添加 CultureInfo 类型的参数,并将其与 char.ToUpper 等方法一起使用> 满足全球化的要求。

I was asked a similar question yesterday and my answer is like:

public static partial class StringExtensions {
    public static String InvertCase(this String t) {
        Func<char, String> selector=
            c => (char.IsUpper(c)?char.ToLower(c):char.ToUpper(c)).ToString();

        return t.Select(selector).Aggregate(String.Concat);
    }
}

You can easily change the method signature to add a parameter of type CultureInfo, and use it with methods like char.ToUpper for a requirement of globalization.

愚人国度 2024-09-25 16:20:39

比这里列出的其他一些方法快一点,它很好,因为它使用 Char 算术!

    var line = "someStringToSwapCase";

    var charArr = new char[line.Length];

    for (int i = 0; i < line.Length; i++)
    {
        if (line[i] >= 65 && line[i] <= 90)
        {
            charArr[i] = (char)(line[i] + 32);
        }
        else if (line[i] >= 97 && line[i] <= 122)
        {
            charArr[i] = (char)(line[i] - 32);
        }
        else
        {
            charArr[i] = line[i];
        }
    }

    var res = new String(charArr);

A little bit faster than some other methods listed here and it is nice because it uses Char arithmetics!

    var line = "someStringToSwapCase";

    var charArr = new char[line.Length];

    for (int i = 0; i < line.Length; i++)
    {
        if (line[i] >= 65 && line[i] <= 90)
        {
            charArr[i] = (char)(line[i] + 32);
        }
        else if (line[i] >= 97 && line[i] <= 122)
        {
            charArr[i] = (char)(line[i] - 32);
        }
        else
        {
            charArr[i] = line[i];
        }
    }

    var res = new String(charArr);
红颜悴 2024-09-25 16:20:39

这将对您有更多帮助..因为在这里我没有直接使用函数。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Practice
{
    class Program
    {
        static void Main(string[] args)
        {
            char[] new_str = new char[50];
            string str;
            int ch;
            Console.Write("Enter String : ");
            str = Console.ReadLine();

            for (int i = 0; i < str.Length; i++)
            {
                ch = (int)str[i];
                if (ch > 64 && ch < 91)
                {
                    ch = ch + 32;
                    new_str[i] = Convert.ToChar(ch);
                }
                else
                {
                    ch = ch - 32;
                    new_str[i] = Convert.ToChar(ch);
                }
            }
            Console.Write(new_str);

            Console.ReadKey();
        }
    }
}

我相信这也适合你..谢谢。

This will helps you more.. because here i have not use directly function.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Practice
{
    class Program
    {
        static void Main(string[] args)
        {
            char[] new_str = new char[50];
            string str;
            int ch;
            Console.Write("Enter String : ");
            str = Console.ReadLine();

            for (int i = 0; i < str.Length; i++)
            {
                ch = (int)str[i];
                if (ch > 64 && ch < 91)
                {
                    ch = ch + 32;
                    new_str[i] = Convert.ToChar(ch);
                }
                else
                {
                    ch = ch - 32;
                    new_str[i] = Convert.ToChar(ch);
                }
            }
            Console.Write(new_str);

            Console.ReadKey();
        }
    }
}

I am sure this will also works for you.. Thank you.

記憶穿過時間隧道 2024-09-25 16:20:39

下面的代码仅对每个字母进行 2 次函数调用。我们不检查 IsLetter 是否存在,而是在必要时应用大写/小写。

    string result="";
    foreach (var item in S)
        {
        if (char.ToLower(item) != item )
            result+= char.ToLower(item);
        else
            result+= char.ToUpper(item);
        }

也可以(尽管可读性较差)创建一个额外的变量,并在检查之前将其设置为 char.ToLower(item),将一个函数调用交换为一个额外的变量,这样:

    string result="";
    foreach (var item in S)
        {
        var temp=char.ToLower(item);
        if (temp != item )
            result+= temp;
        else
            result+= char.ToUpper(item);
        }

Code below makes only 2 function calls to each letter. Instead of checking if IsLetter, we just apply upper/lowercase if necessary.

    string result="";
    foreach (var item in S)
        {
        if (char.ToLower(item) != item )
            result+= char.ToLower(item);
        else
            result+= char.ToUpper(item);
        }

It would be also possible (tho less readable) to create an extra variable and set it to char.ToLower(item) before the check, exchanging one function call for one extra variable, thie way:

    string result="";
    foreach (var item in S)
        {
        var temp=char.ToLower(item);
        if (temp != item )
            result+= temp;
        else
            result+= char.ToUpper(item);
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文