📜  find-text-in-string-with-c-sharp - C# (1)

📅  最后修改于: 2023-12-03 14:41:11.744000             🧑  作者: Mango

在C#中查找字符串的方法

在 C# 中,查找字符串是一项常见操作。无论是从用户输入中查找特定的单词,还是从文件中搜索内容,都需要使用一些方法来查找指定的文本。下面介绍几种常见的字符串查找方式。

IndexOf

IndexOf 方法用于查找字符串中第一个匹配项的索引。如果未找到任何匹配项,则返回 -1。

string str = "hello world";
int index = str.IndexOf("world");
if (index != -1)
{
    Console.WriteLine($"\"world\" found at index {index}");
}

输出结果:

"world" found at index 6
LastIndexOf

LastIndexOf 方法用于查找字符串中最后一个匹配项的索引。如果未找到任何匹配项,则返回 -1。

string str = "hello world";
int index = str.LastIndexOf("o");
if (index != -1)
{
    Console.WriteLine($"Last \"o\" found at index {index}");
}

输出结果:

Last "o" found at index 7
Contains

Contains 方法返回一个布尔值,指示指定的字符串是否出现在此字符串中。

string str = "hello world";
bool isExist = str.Contains("world");
if (isExist)
{
    Console.WriteLine("\"world\" exists in the string.");
}

输出结果:

"world" exists in the string.
StartsWith

StartsWith 方法返回一个布尔值,指示此字符串是否以指定的前缀开头。

string str = "hello world";
bool isStartWith = str.StartsWith("hello");
if (isStartWith)
{
    Console.WriteLine("The string starts with \"hello\".");
}

输出结果:

The string starts with "hello".
EndsWith

EndsWith 方法返回一个布尔值,指示此字符串是否以指定的后缀结尾。

string str = "hello world";
bool isEndWith = str.EndsWith("world");
if (isEndWith)
{
    Console.WriteLine("The string ends with \"world\".");
}

输出结果:

The string ends with "world".