如何检查字符串是否包含 C# 中的字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8879774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:56:05  来源:igfitidea点击:

How can I check if a string contains a character in C#?

c#string

提问by Samantha J T Star

Is there a function I can apply to a string that will return true of false if a string contains a character.

是否有一个函数可以应用于字符串,如果字符串包含一个字符,该函数将返回 true 或 false。

I have strings with one or more character options such as:

我有包含一个或多个字符选项的字符串,例如:

var abc = "s";
var def = "aB";
var ghi = "Sj";

What I would like to do for example is have a function that would return true or false if the above contained a lower or upper case "s".

例如,我想做的是有一个函数,如果上面包含小写或大写的“s”,则该函数将返回 true 或 false。

if (def.Somefunction("s") == true) { }

Also in C# do I need to check if something is true like this or could I just remove the "== true" ?

同样在 C# 中,我是否需要检查这样的事情是否属实,或者我可以删除“== true”吗?

采纳答案by Anders Tornblad

You can use the extension method .Contains()from the namespace System.Linq:

您可以使用.Contains()命名空间 System.Linq 中的扩展方法:

using System.Linq;

    ...

    if (abc.ToLower().Contains('s')) { }

And no, to check if a boolean expression is true, you don't need == true

不,要检查布尔表达式是否为真,您不需要 == true

Since the Containsmethod is an extension method, my solution appeared to be confusing to some. Here are two versions that don't require you to add using System.Linq;:

由于该Contains方法是一种扩展方法,因此我的解决方案对某些人来说似乎令人困惑。以下是不需要您添加的两个版本using System.Linq;

if (abc.ToLower().IndexOf('s') != -1) { }

// or:

if (abc.IndexOf("s", StringComparison.CurrentCultureIgnoreCase) != -1) { }

Update

更新

If you want to, you can write your own extensions method for easier reuse:

如果需要,您可以编写自己的扩展方法以便于重用:

public static class MyStringExtensions
{
    public static bool ContainsAnyCaseInvariant(this string haystack, char needle)
    {
        return haystack.IndexOf(needle, StringComparison.InvariantCultureIgnoreCase) != -1;
    }

    public static bool ContainsAnyCase(this string haystack, char needle)
    {
        return haystack.IndexOf(needle, StringComparison.CurrentCultureIgnoreCase) != -1;
    }
}

Then you can call them like this:

然后你可以这样调用它们:

if (def.ContainsAnyCaseInvariant('s')) { }
// or
if (def.ContainsAnyCase('s')) { }

In most cases when dealing with user data, you actually want to use CurrentCultureIgnoreCase(or the ContainsAnyCaseextension method), because that way you let the system handle upper/lowercase issues, which depend on the language. When dealing with computational issues, like names of HTML tags and so on, you want to use the invariant culture.

在大多数情况下,在处理用户数据时,您实际上想要使用CurrentCultureIgnoreCase(或ContainsAnyCase扩展方法),因为这样可以让系统处理取决于语言的大写/小写问题。在处理计算问题时,例如 HTML 标签的名称等,您希望使用不变文化。

For example: In Turkish, the uppercase letter Iin lowercase is ?(without a dot), and not i(with a dot).

例如:在土耳其语中,I小写的大写字母是?(不带点),而不是i(带点)

回答by bniwredyc

bool containsCharacter = test.IndexOf("s", StringComparison.OrdinalIgnoreCase) >= 0;

回答by tobias86

The following should work:

以下应该工作:

var abc = "sAb";
bool exists = abc.IndexOf("ab", StringComparison.CurrentCultureIgnoreCase) > -1;

回答by Shamim Hafiz

Use the function String.Contains();

使用函数 String.Contains();

an example call,

一个示例调用,

abs.Contains("s"); // to look for lower case s

hereis more from MSDN.

这里有更多来自 MSDN。

回答by Rich O'Kelly

You can use the IndexOfmethod, which has a suitable overload for string comparison types:

您可以使用该IndexOf方法,该方法具有适合字符串比较类型的重载:

if (def.IndexOf("s", StringComparison.OrdinalIgnoreCase) >= 0) ...

Also, you would not need the == true, since an if statement only expects an expression that evaluates to a bool.

此外,您不需要== true,因为 if 语句只需要一个计算结果为 a 的表达式bool

回答by Sergejs

It will be hard to work in C# without knowing how to work with strings and booleans. But anyway:

如果不知道如何使用字符串和布尔值,就很难在 C# 中工作。但无论如何:

        String str = "ABC";
        if (str.Contains('A'))
        { 
            //...
        }

        if (str.Contains("AB"))
        { 
            //...
        }

回答by Karan Shah

here is an example what most of have done

这是大多数人所做的一个例子

using System;

class Program
{
    static void Main()
    {
        Test("Dot Net Perls");
        Test("dot net perls");
    }

    static void Test(string input)
    {
        Console.Write("--- ");
        Console.Write(input);
        Console.WriteLine(" ---");
        //
        // See if the string contains 'Net'
        //
        bool contains = input.Contains("Net");
        //
        // Write the result
        //
        Console.Write("Contains 'Net': ");
        Console.WriteLine(contains);
        //
        // See if the string contains 'perls' lowercase
        //
        if (input.Contains("perls"))
        {
            Console.WriteLine("Contains 'perls'");
        }
        //
        // See if the string contains 'Dot'
        //
        if (!input.Contains("Dot"))
        {
            Console.WriteLine("Doesn't Contain 'Dot'");
        }
    }
}

回答by Aphelion

You can create your own extention method if you plan to use this a lot.

如果您打算经常使用它,您可以创建自己的扩展方法。

public static class StringExt
{
    public static bool ContainsInvariant(this string sourceString, string filter)
    {
        return sourceString.ToLowerInvariant().Contains(filter);
    }
}

example usage:

用法示例:

public class test
{
    public bool Foo()
    {
        const string def = "aB";
        return def.ContainsInvariant("s");
    }
}