字符串字面量与 C# 中的字符串对象
字符串字面量
字符串字面量或常量用双引号 " 或 @ 进行括起。字符串包含类似于字符字面的字符:普通字符、转义序列和通用字符。
以下是字符串字面量的一些示例 −
Hello, World" "Welcome, \
以下是一个显示字符串字面量用法示例 −
示例
using System; namespace Demo { class Program { static void Main(string[] args) { // string string str1 ="Hello, World"; Console.WriteLine(str1); // Multi-line string string str2 = @"Welcome, Hope you are doing great!"; Console.WriteLine(str2); } } }
Learn C# in-depth with real-world projects through our C# certification course. Enroll and become a certified expert to boost your career.
字符串对象
使用以下其中一种方法创建字符串对象 −
- 将字符串字面量赋值给 String 变量
- 使用 String 类构造函数
- 使用字符串连接运算符 (+)
- 通过检索属性或调用返回字符串的方法
- 通过调用格式化方法将值或对象转换为其字符串表示形式
以下是如何创建字符串对象并比较两个字符串 −
示例
using System; namespace Demo { class Program { static void Main(string[] args) { string str1 = "John"; string str2 = "Andy"; if (String.Compare(str1, str2) == 0) { Console.WriteLine(str1 + " and " + str2 + " are equal strings."); } else { Console.WriteLine(str1 + " and " + str2 + " are not equal strings."); } Console.ReadKey() ; } } }
广告