本文讲解字符串的比较:忽略大小写与不忽略大小写,内存地址是否相同。
当需要对两个字符串的值进行比较和排序而不需要考虑语言惯例时,请使用基本的序号比较。基本的序号比较 (Ordinal) 是区分大小写的,这意味着两个字符串的字符必须完全匹配:“and”不等于“And”或“AND”。常用的变量有 OrdinalIgnoreCase,它将匹配“and”、“And”和“AND”;还有 StringComparison.OrdinalIgnoreCase,它常用于比较文件名、路径名和网络路径,以及其值不随用户计算机的区域设置的更改而变化的任何其他字符串。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class ReplaceSubstrings
{
string searchFor;
string replaceWith;
static void Main(string[] args)
{
// Internal strings that will never be localized.
string root = @"C:\users";
string root2 = @"C:\Users";
// 不忽略大小写 Use the overload of the Equals method that specifies a StringComparison.
// Ordinal is the fastest way to compare two strings.
bool result = root.Equals(root2, StringComparison.Ordinal);
Console.WriteLine("Ordinal comparison: {0} and {1} are {2}", root, root2,
result ? "equal." : "not equal.");
//忽略大小写 To ignore case means "user" equals "User". This is the same as using
// String.ToUpperInvariant on each string and then performing an ordinal comparison.
result = root.Equals(root2, StringComparison.OrdinalIgnoreCase);
Console.WriteLine("Ordinal ignore case: {0} and {1} are {2}", root, root2,
result ? "equal." : "not equal.");
// A static method is also available.
bool areEqual = String.Equals(root, root2, StringComparison.Ordinal);
// String interning. Are these really two distinct objects?编译器会将它们存储在同一位置
string a = "The computer ate my source code.";
string b = "The computer ate my source code.";
// ReferenceEquals returns true if both objects
// point to the same location in memory.
if (String.ReferenceEquals(a, b))
Console.WriteLine("a and b are interned.");
else
Console.WriteLine("a and b are not interned.");
// Use String.Copy method to avoid interning.使用 String..::.Copy 方法可避免存储在同一位置,
string c = String.Copy(a);
if (S