希望有人可以帮助我.我刚刚学习C#,我有一个简单的问题.
我有一个变量,我想检查是否存在于另一个字符串中.就像是
if ( test contains "abc" ) {
}
Run Code Online (Sandbox Code Playgroud)
有没有一种简单的方法在C#中执行此操作
Akr*_*hda 73
if (stringValue.Contains(anotherStringValue))
{
// Do Something //
}
Run Code Online (Sandbox Code Playgroud)
string MainString = "String Manipulation";
string SearchString = "pul";
int FirstChr = MainString.IndexOf(SearchString);
Run Code Online (Sandbox Code Playgroud)
此代码显示如何在字符串中搜索子字符串,并返回起始位置的索引位置或-1(表示未找到该字符串)。
您还可以使用Contains(),Contains是字符串类型的实例方法,这意味着您可以在程序中的特定字符串上调用它。它有一个布尔结果,如果找到该参数则为true,否则为false。
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'");
}
}
}
Run Code Online (Sandbox Code Playgroud)
有关任何有关字符串的内容,请检查C#字符串函数和操作。
小智 5
使用String.Contains(...)可能不是一个好主意。
String.Contains(...)进行区分大小写的顺序比较。因此,请注意大小写匹配。
当然可以使用,ToLower()或者ToUpper()在您检查之前
if (stringValue.ToUpper().Contains("FIND_THIS"))
{
// Do Something //
}
Run Code Online (Sandbox Code Playgroud)
是区分大小写的搜索的另一个很好的变体。
| 归档时间: |
|
| 查看次数: |
81082 次 |
| 最近记录: |