如何在C#中检查字符串是否包含字符? [英] How can I check if a string contains a character in C#?

查看:622
本文介绍了如何在C#中检查字符串是否包含字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

例如,我想做的是有一个函数,如果上面的函数返回true或false

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".

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

在C#中,我还需要检查是否为真,或者我可以删除 == true?

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

推荐答案

您可以使用扩展方法 .Contains() 。 Linq:

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

using System.Linq;

    ...

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

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

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

由于 Contains 方法是扩展方法,所以我的解决方案似乎有些困惑。这是两个版本,不需要您使用System.Linq添加

Since the Contains method 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;:

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

// or:

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

更新

如果愿意,您可以编写自己的扩展方法以方便重用:

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')) { }

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

In most cases when dealing with user data, you actually want to use CurrentCultureIgnoreCase (or the ContainsAnyCase extension 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.

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

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

这篇关于如何在C#中检查字符串是否包含字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆