一:拼接的3种方法
1.1 使用 + 或 += 进行拼接:
string str="";
str += 1+2+3+4;//输出 10
string str="";
str += "" + 1 + 2 + 3 + 4;//输出 1234
string str="";
str += 1 + 2 + "" + ( 3 + 4 );//输出 37
string str="";
str +="1"+4+true;//输出 14True
true转为字符串是True。
拼接技巧:
主要看第一个拼的是什么,或使用括号来破坏
当string型数据参与 +或+= 运算时,就变成了拼接而不是加法运算。因为调用了 .ToString()
用+或+=拼接,是用符号唯一方法 不能用-*/%….
1.2 string.Format() 格式化输出
string str2 = string.Format("我是{0}, 我今年{1}岁", "小明", 18);
string message = string.Format("The number is {0}.", number);
string str = "我叫{0},今年{1}岁";
string result = string.Format(str,"小明",18);
占位符和数据都是可多不可少
实例:控制台打印方法Console.WriteLine() 和 Console.Write() 就是调用了 string.Format()
1.3 插值字符串
C# 6.0引入的一个特性 $"{}{}{}"
string firstName = "John";
string lastName = "Doe";
string fullName = $"{firstName} {lastName}";
int age = 30;
string message = $"Hello, I am {firstName} {lastName} and I am {age} years old.";
对插入值进行格式化
//对插入中进行格式化
int number = 123456;
string formattedNumber = $"Formatted number: {number:000000}";
二:字符串格式化输出
Console.WriteLine("{0}+{1}={2}",a,b,a+b);
//替代标记:不存在不可以写,可以重复写
//替代值:不一定都被用到
string.Format() 一种格式化字符串的API
2.1 基本语法
string formattedString = string.Format(formatString, arg0);
string formattedString = string.Format(formatString, arg0, arg1, ...);
2.2 参数说明
-
formatString
:一个复合格式字符串,它包含零个或多个由花括号{
和}
包围的索引占位符,这些索引对应于后续参数的顺序。 -
arg0, arg1, ...
:要格式化的对象。
2.3 简单格式化
string message = string.Format("The number is {0}.", number);
string message = string.Format("The number is {0} and the text is {1}.", number, text);
2.4 使用索引和属性格式化信息
String.Format()
还允许指定格式信息,比如数字的格式化、日期的格式化等。
int number = 1234;
string message = string.Format("Formatted number: {0:N2}", number);
Console.WriteLine(message); // 输出: Formatted number: 1,234.00
在这个例子中,:N2
指定了数值应该以数字格式(N
)显示,保留两位小数。
var item = new { Name = "Item1", Price = 19.99m };
string message = string.Format("Item: {0}, Price: {1:C}", item.Name, item.Price);
Console.WriteLine(message); // 输出: Item: Item1, Price: $19.99
在这个例子中,{0}
是 Name
的占位符,而 {1:C}
表示将 Price
格式化为货币格式。
2.5 自定义格式化方法
String.Format()
还支持自定义的格式化字符串和转换逻辑,这可以通过实现 IFormatProvider
接口来完成。