Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

C# 判断字符串是否全部为英文

  1. User

    C# 判断字符串是否全部为英文

  2. Assistant

    如果想判断一个字符串是否全部为英文,可以使用正则表达式进行匹配。

    以下是一个示例代码:

    using System;
    using System.Text.RegularExpressions;
    
    class Program
    {
        static void Main(string[] args)
        {
            string str = "Hello World";
            if (IsEnglish(str))
            {
                Console.WriteLine("The string is all English.");
            }
            else
            {
                Console.WriteLine("The string is not all English.");
            }
        }
    
        static bool IsEnglish(string str)
        {
            return Regex.IsMatch(str, @"^[a-zA-Z]+$");
        }
    }
    

    在上面的例子中,我们将字符串传入 IsEnglish 方法中,然后使用正则表达式 ^[a-zA-Z]+$ 进行判断。这个正则表达式的意思是“匹配由 26 个英文字母(大小写不限)组成的字符串”。如果符合这个条件,则返回 true,否则返回 false。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.