十、【C#】字符串拼接

十、字符串拼接(C#)


提示:笔记中的内容是我自己的理解,可能会存在理解错误,也欢迎大家指正\( ̄︶ ̄*\))

字符串拼接

1. 拼接方式一

1.1 通过 “+” 号进行拼接

(1)、字符串拼接方式一:“字符串” 不存在算术运算符,所以不能进行计算。但可以通过 “+” 号来进行字符串拼接。

举例1:

static void Main(string[] args)
{
    string str = "123";
    str = str + "456";
    Console.WriteLine(str);

    str = "123";
    str = str + (1 + 2 + 3);  //先计算"1+2+3"的结果,然后将运算结果拼接到"str"中。
    Console.WriteLine(str);
}

//输出结果为:
123456
1236

举例2:

注意:当一个 “字符串” 加一个 “整型” 时,系统会默认调用 “ToString方法” 将 “整型” 转换为 “string类型”。

static void Main(string[] args)
{
    string str = "Ciye";
    
    //系统会默认调用"ToString方法"将"整型"的"1"转换为"string类型"的"1"。
    str = str + 1;  //不是进行算术运算,而是进行拼接。
    Console.WriteLine(str);
}

//输出结果为:
Ciye1

1.2 通过复合运算符 “+=” 号进行拼接

举例:

static void Main(string[] args)
{
    string str = "123";
    str += "1" + 4 + true;
    Console.WriteLine(str);
}

//输出结果为:
12314True
static void Main(string[] args)
{
    string str = "123";
    str += 1 + 2 + 3;  //"+="右侧没有字符串,则计算出"1+2+3"的结果,然后拼接到"str"中。
    Console.WriteLine(str);

    str = "123";
    //"+="右侧有"空字符串",并且位于最前面,则将"1"、"2"、"3"拼接到"空字符串"中,然后再跟"str"进行拼接。
    str += " " + 1 + 2 + 3;
    Console.WriteLine(str);

    str = "123";
    //"+="右侧有"空字符串",但不位于最前面,则先计算"1+2"的结果,然后和"空字符串"进行拼接,并且"3"、"4"位于"空字符串"后面,则将"3"、"4"拼接到"空字符串"后面,最后再与"str"进行拼接。
    str += 1 + 2 + " " + 3 + 4;
    Console.WriteLine(str);
}

//输出结果为:
1236
123 123
1233 34

2. 拼接方式二

(1)、语法:

string.Format("待拼接的内容", 内容1, 内容2, ......);

(2)、拼接内容中的固定规则:

  • 想要被拼接的内容用 “占位符” 替代。格式为:“{数字}”。“数字” 从 “0 ~ n” 依次往后。

举例:

static void Main(string[] args)
{
    string str;
    str = string.Format("我是{0},我今年{1}岁,我想要{2}", "Ciye", 18, "xxx");
    Console.WriteLine(str);
    
    str = string.Format("{0}{1}{2}", 1, true, false);
	Console.WriteLine(str);
}

//输出结果为:
我是Ciye,我今年18,我想要xxx
1TrueFalse

3. 控制台打印拼接

举例:

static void Main(string[] args)
{
    Console.WriteLine("A{0}B{1}C{2}", 1, true, false);
    Console.Write("A{0}B{1}C{2}", 1, true, false);
}

//输出结果为:
A1BTrueCFalse
A1BTrueCFalse

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值