C# 如何判断字符串最后一位是不是逗号

要判断 C# 中的字符串是否以逗号结尾,有几种方法可以实现:

方法1:使用 SubstringEndsWith 方法

string str = "Hello, World,";
bool endsWithComma = str.EndsWith(","); // 判断字符串是否以逗号结尾
Console.WriteLine(endsWithComma); // 输出 True

这种方法使用 EndsWith 方法检查字符串是否以逗号结尾。

方法2:使用 TrimEndstring 对象的 [] 访问器

string str = "Hello, World,";
bool endsWithComma = str.TrimEnd()[str.Length - 1] == ','; // 判断字符串是否以逗号结尾
Console.WriteLine(endsWithComma); // 输出 True

这种方法使用 TrimEnd 方法删除字符串末尾的空白字符,然后使用 [] 访问器来访问字符串的最后一个字符,并与逗号进行比较。

无论使用哪种方法,只要判断结果为 True,则表示字符串的最后一位是逗号。

你可能感兴趣的:(锦集,c#,开发语言)