string str1 = "Hello";string str2 = "Hello";bool result = str1 == str2; // 结果为 true2. 字符串.Equals 方法使用方法:

c#怎么比较字符串内容

来源:这里教程网 时间:2026-02-21 16:48:29 作者:

如何在 C# 中比较字符串内容

在 C# 中,字符串内容的比较可以通过多种方法实现:

1. 字符相等操作符(== 和 !=)

使用方法:

<code class="c#">string str1 = "Hello";
string str2 = "Hello";
bool result = str1 == str2; // 结果为 true</code>

2. 字符串.Equals 方法

使用方法:

<code class="c#">result = str1.Equals(str2); // 结果为 true
// 指定大小写敏感或不敏感比较
result = str1.Equals(str2, StringComparison.InvariantCultureIgnoreCase); // 结果仍为 true</code>

3. 字符串.Compare 方法

使用方法:

<code class="c#">int comparisonResult = str1.CompareTo(str2);
// 如果 str1 等于 str2,则返回 0
if (comparisonResult == 0)
{
    // 省略代码
}
// 如果 str1 小于 str2,则返回小于 0 的值
else if (comparisonResult < 0)
{
    // 省略代码
}
// 如果 str1 大于 str2,则返回大于 0 的值
else
{
    // 省略代码
}</code>

4. 字符串.CompareOrdinal 方法

使用方法:

<code class="c#">comparisonResult = String.CompareOrdinal(str1, str2);
// 与 String.Compare 方法相同,但比较是基于二进制值(而非文化规则)</code>

5. 字符串.StartsWith 和 String.EndsWith 方法

使用方法:

<code class="c#">bool startsWith = str1.StartsWith("Hel"); // 结果为 true
bool endsWith = str1.EndsWith("lo"); // 结果为 true</code>

根据需要选择最合适的方法来比较字符串内容。

相关推荐