本文讲解字符串的比较:忽略大小写与不忽略大小写,内存地址是否相同。
当需要对两个字符串的值进行比较和排序而不需要考虑语言惯例时,请使用基本的序号比较。基本的序号比较 (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 (String.ReferenceEquals(a, c))
Console.WriteLine("a and c are interned.");
else
Console.WriteLine("a and c are not interned.");
Console.ReadLine();
}
}
}
字符串的分割:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class TestStringSplit
{
static void Main()
{
char[] delimiterChars = { ' ', ',', '.', ':', '\t','\r' };
string text = "one\ttwo three:four,five six seven";
System.Console.WriteLine("Original text: '{0}'", text);
string[] words = text.Split(delimiterChars);
System.Console.WriteLine("{0} words in text:", words.Length);
foreach (char myc in delimiterChars)
{
System.Console.WriteLine(myc);
}
foreach (string s in words)
{
System.Console.WriteLine(s);
}
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
}
字符串的 索引、部分选取
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
//yngqq@2024年9月3日15:22:45
namespace ConsoleApp1
{
class StringSearch
{
static void Main()
{
string str = "Extension methods have all the capabilities of regular static methods.";
//.IndexOf 字符串的索引位置,从0开始。
System.Console.WriteLine(str.IndexOf("E"));
// Write the string and include the quotation marks.
System.Console.WriteLine("\"{0}\"", str);
// Simple comparisons are always case sensitive!
bool test1 = str.StartsWith("extension");
System.Console.WriteLine("Starts with \"extension\"? {0}", test1);
// For user input and strings that will be displayed to the end user,
// use the StringComparison parameter on methods that have it to specify how to match strings.
bool test2 = str.StartsWith("extension", System.StringComparison.CurrentCultureIgnoreCase);
System.Console.WriteLine("Starts with \"extension\"? {0} (ignoring case)", test2);
bool test3 = str.EndsWith(".", System.StringComparison.CurrentCultureIgnoreCase);
System.Console.WriteLine("Ends with '.'? {0}", test3);
// This search returns the substring between two strings, so
// the first index is moved to the character just after the first string.
int first = str.IndexOf("methods") + "methods".Length;
int last = str.LastIndexOf("methods");
System.Console.WriteLine("methods".Length + " "+ first + " "+ last );
//子字符串substring,开始的位置索引(first),总长度减去最后一个字的长度减去开始的位置(last - first)
//选取部分字符:.substring方法
string str2 = str.Substring(first, last - first);
System.Console.WriteLine("Substring between \"methods\" and \"methods\": '{0}'", str2);
// Keep the console window open in debug mode
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
/*
Output:
"0
"Extension methods have all the capabilities of regular static methods."
Starts with "extension"? False
Starts with "extension"? True (ignoring case)
Ends with '.'? True
7 17 62
Substring between "methods" and "methods": ' have all the capabilities of regular static '
Press any key to exit.
*/
}
下图为正则表达式查找字符串中是否包含特定字符:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
//yngqq@2024年9月3日15:22:45
namespace ConsoleApp1
{
class TestRegularExpressions
{
static void Main()
{
string[] sentences =
{
"cow over the moon",
"Betsy the Cow",
"cowering in the corner",
"no match here"
};
string sPattern = "cow";
foreach (string s in sentences)
{//在控制台输出 s 变量的值,并确保它至少占据24个字符的宽度,不足的部分将以空格填充在左侧
System.Console.Write("{0,24}", s);
System.Console.Write("\n\n\n\n");
System.Console.WriteLine(s); //( "{0}",s);
//正则表达式的匹配结果是一个布尔类型值,真、假,表示匹配成功或不成功
bool mybool = System.Text.RegularExpressions.Regex.IsMatch(s, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Console.WriteLine(mybool);
//三个参数:原始字符串,需要查找的字符串,匹配方法
if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
{
System.Console.WriteLine(" (match for '{0}' found)", sPattern);
}
else
{
System.Console.WriteLine();
}
}
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
/* Output:
cow over the moon
cow over the moon
True
(match for 'cow' found)
Betsy the Cow
Betsy the Cow
True
(match for 'cow' found)
cowering in the corner
cowering in the corner
True
(match for 'cow' found)
no match here
no match here
False
Press any key to exit.
*/
}
下例为尝试将字符串转为数字类型:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
//yngqq@2024年9月3日15:22:45
namespace ConsoleApp1
{
class TestRegularExpressions
{
static void Main()
{
string numString = "1287543"; //"1287543.0" will return false for a long
string numString1 = "1287543.0"; //"1287543.0" will return false for a long
long number1 = 0;
//parse的意思 英 [pɑːz] v. 从语法上分析n. 从语法上分析
/*在C#中,out 关键字在方法参数列表中有特殊的用途,
* 它指示该参数是一个输出参数。这意味着方法将会向这个参数写入一个值,
* 而不是从它读取值(尽管在方法内部,你也可以读取它的值,但主要目的是向它写入值)。
* out 参数不需要在调用方法之前被初始化,因为调用方法时,方法的实现会负责给它赋值。
下面是字符串转换成long型数字后,输出到number1变量中*/
bool canConvert = long.TryParse(numString, out number1);
Console.WriteLine(number1);
if (canConvert == true)
Console.WriteLine("number1 now = {0}", number1);
else
Console.WriteLine("numString is not a valid long");
bool canConvert1 = long.TryParse(numString1, out number1);
if (canConvert1 == true)
Console.WriteLine("number1 now = {0}", number1);
else
Console.WriteLine("numString1 {0} is not a valid long", numString1);
byte number2 = 0;//初始化一个字节类型的变量
numString = "255"; // A value of 256 will return false
canConvert = byte.TryParse(numString, out number2);
if (canConvert == true)
Console.WriteLine("number2 now = {0}", number2);
else
Console.WriteLine("numString is not a valid byte");
numString1 = "256"; // A value of 256 will return false
canConvert = byte.TryParse(numString1, out number2);
if (canConvert == true)
Console.WriteLine("number2 now = {0}", number2);
else
Console.WriteLine("numString1 \"{0}\" is not a valid byte", numString1);
decimal number3 = 0;
numString = "27.3"; //"27" is also a valid decimal
canConvert = decimal.TryParse(numString, out number3);
if (canConvert == true)
Console.WriteLine("number3 now = {0}", number3);
else
Console.WriteLine("number3 is not a valid decimal");
Console.ReadKey();
}
}
}
以下为字符串跟日期类型的转换:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
//yngqq@2024年9月3日15:22:45
namespace ConsoleApp1
{
class TestRegularExpressions
{
static void Main()
{
// Date strings are interpreted according to the current culture.
// If the culture is en-US, this is interpreted as "January 8, 2008",
// but if the user's computer is fr-FR, this is interpreted as "August 1, 2008"
string date = "01/08/2008";
DateTime dt = Convert.ToDateTime(date);
Console.WriteLine("Year: {0}, Month: {1}, Day: {2}", dt.Year, dt.Month, dt.Day);
string date1 = "2024年9月3日16:06:21";
DateTime dt1 = Convert.ToDateTime(date1);
Console.WriteLine("{0},{1},{2}", dt1.Hour,dt1.Minute ,dt1.Second );
//输出当前时间
DateTime dtnow =DateTime.Now ;
Console.WriteLine("现在是:{0}",dtnow.ToString() );
// Specify exactly how to interpret the string.
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
// Alternate choice: If the string has been input by an end user, you might
// want to format it according to the current culture:
// IFormatProvider culture = System.Threading.Thread.CurrentThread.CurrentCulture;
DateTime dt2 = DateTime.Parse(date, culture, System.Globalization.DateTimeStyles.AssumeLocal);
Console.WriteLine("Year: {0}, Month: {1}, Day {2}", dt2.Year, dt2.Month, dt2.Day);
Console.ReadLine();
/* Output (assuming first culture is en-US and second is fr-FR):
Year: 2008, Month: 1, Day: 8
Year: 2008, Month: 8, Day 1
*/
}
}
}