ToString 也可以自定义补零格式化:
(15).ToString("000"); // 结果:015
(15).ToString("value is 0"); // 结果:value is 15
(10.456).ToString("0.00"); // 结果:10.46
(10.456).ToString("00"); // 结果:10
(10.456).ToString("value is 0.0"); // 结果:value is 10.5
转换为二进制、八进制、十六进制输出:
int number = 15; Convert.ToString(number, 2); // 结果:1111 Convert.ToString(number, 8); // 结果:17 Convert.ToString(number, 16); // 结果:f
自定义格式化器:
public class CustomFormat : IFormatProvider, ICustomFormatter
{
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (!this.Equals(formatProvider))
{
return null;
}
if (format == "Reverse")
{
return string.Join("", arg.ToString().Reverse());
}
return arg.ToString();
}
public object GetFormat(Type formatType)
{
return formatType == typeof(ICustomFormatter) ? this : null;
}
}
使用自定义格式化器:
String.Format(newCustomFormat(), "-> {0:Reverse} <-", "Hello World");
// 输出:-> dlroW olleH <-
字符串拼接
将数组中的字符串拼接成一个字符串:
var parts = new[] { "Foo", "Bar", "Fizz", "Buzz"};
var joined = string.Join(", ", parts);
// joined = "Foo, Bar, Fizz, Buzz"
以下四种方式都可以达到相同的字符串拼接的目的:
string first = "Hello";
string second = "World";
string foo = first + " " + second;
string foo = string.Concat(first, " ", second);
string foo = string.Format("{0} {1}", firstname, lastname);
string foo = $"{firstname} {lastname}";
字符串内插法
简单用法:
var name = "World";
var str =$"Hello, {name}!";
// str = "Hello, World!"
带日期格式化:
var date = DateTime.Now;
var str = $"Today is {date:yyyy-MM-dd}!";
补齐格式化(Padding):
var number = 42;
// 向左补齐
var str = $"The answer to life, the universe and everything is {number, 5}.";
// str = "The answer to life, the universe and everything is ___42." ('_'表示空格)
// 向右补齐
var str = $"The answer to life, the universe and everything is ${number, -5}.";
// str = "The answer to life, the universe and everything is 42___."
结合内置快捷字母格式化:
var amount = 2.5;
var str = $"It costs {amount:C}";
// str = "¥2.50"
var number = 42;
var str = $"The answer to life, the universe and everything is {number, 5:f1}.";
// str = "The answer to life, the universe and everything is ___42.1"
以上就是c# 字符串操作总结的详细内容,更多关于C#字符串操作的资料请关注易采站长站其它相关文章!










