C# 搜索字符串
最后修改于 2024 年 1 月 26 日
在本文中,我们将展示如何在 C# 语言中搜索字符串。
C# 提供了几种搜索字符串的方法,包括 Contains、StartsWith、EndsWith、IndexOf 和 LastIndexOf。 更复杂的搜索操作可以使用 Regex 类执行。
C# Contains
Contains 方法返回一个布尔值,指示子字符串是否出现在指定的字符串中。
var text = "An old hawk in the sky";
var word = "hawk";
if (text.Contains(word))
{
Console.WriteLine($"The text contains the {word} word");
} else
{
Console.WriteLine($"The text does not contain the {word} word");
}
在此示例中,我们在句子中查找 hawk 单词。
$ dotnet run The text contains the hawk word
C# StartsWith 和 EndsWith
StartsWith 确定字符串的开头是否与指定的字符串匹配,而 EndsWith 确定字符串的结尾是否与指定的字符串匹配。
var text = "old hawk";
if (text.StartsWith("old"))
{
Console.WriteLine("The text starts with the old string");
} else
{
Console.WriteLine("The text does not with the old string");
}
if (text.EndsWith("hawk"))
{
Console.WriteLine("The text ends with the hawk string");
} else
{
Console.WriteLine("The text does not end with the hawk string");
}
在此示例中,我们展示了这两种方法的用法。
$ dotnet run The text starts with the old string The text ends with the hawk string
C# IndexOf 和 LastIndexOf
IndexOf 方法查找指定的 Unicode 字符或字符串第一次出现的从零开始的索引;如果未找到字符或字符串,则返回 -1。 LastIndexOf 方法查找指定的 Unicode 字符或字符串最后一次出现的从零开始的索引;如果未找到字符或字符串,则返回 -1。
var text = "There is an old hawk in the sky. The sun is shining.";
var word = "is";
int first = text.IndexOf(word);
int last = text.LastIndexOf(word);
Console.WriteLine($"The first index of the word {word}: {first}");
Console.WriteLine($"The last index of the word {word}: {last}");
在此示例中,我们查找 is 单词的第一次和最后一次出现。
$ dotnet run The first index of the word is: 6 The last index of the word is: 41
C# Regex Match
Regex 可用于执行更复杂的搜索操作。 C# 正则表达式教程 更详细地介绍了 C# 中的正则表达式。
Match 的 Success 属性返回一个布尔值,指示匹配是否成功。 NextMatch 方法返回一个新的 Match 对象,其中包含下一次匹配的结果,从上次匹配结束的位置开始。
可以在字符串中使用 Match 的 Index 属性找到匹配项的位置。
using System.Text.RegularExpressions;
var content = @"Foxes are omnivorous mammals belonging to several genera
of the family Canidae. Foxes have a flattened skull, upright triangular ears,
a pointed, slightly upturned snout, and a long bushy tail. Foxes live on every
continent except Antarctica. By far the most common and widespread species of
fox is the red fox.";
var rx = new Regex("fox(es)?", RegexOptions.Compiled |
RegexOptions.IgnoreCase);
Match match = rx.Match(content);
while (match.Success)
{
Console.WriteLine($"{match.Value} at index {match.Index}");
match = match.NextMatch();
}
我们查找 fox 单词的所有出现情况。
var rx = new Regex("fox(es)?", RegexOptions.Compiled |
RegexOptions.IgnoreCase);
我们添加 (es)? 表达式以包含该单词的复数形式。 RegexOptions.IgnoreCase 在不区分大小写的模式下进行搜索。
Match match = rx.Match(content);
while (match.Success)
{
Console.WriteLine($"{match.Value} at index {match.Index}");
match = match.NextMatch();
}
Value 返回匹配的字符串,Index 返回它在文本中的索引。 NextMatch 方法查找下一个匹配项。
$ dotnet run Foxes at index 0 Foxes at index 82 Foxes at index 198 fox at index 300 fox at index 315
来源
在本文中,我们搜索了 C# 语言中的字符串。
作者
列出所有 C# 教程。