C# 字符串拼接

✅作者简介:人工智能专业本科在读,喜欢计算机与编程,写博客记录自己的学习历程。
🍎个人主页:小嗷犬的博客
🍊个人信条:为天地立心,为生民立命,为往圣继绝学,为万世开太平。
🥭本文内容:C# 字符串拼接



通过加号拼接

C# 中,字符串没有相加的数学运算,但它可以通过加号+来进行字符串的拼接:

using System;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "Hello World";
            str = str + 3.14;
            Console.WriteLine(str);
        }
    }
}

也可以和复合赋值运算符+=结合使用:

using System;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "Hello World";
            str += 1 + 2 + 3 + 4;
            Console.WriteLine(str);
        }
    }
}

根据这个性质,我们也可以将其他类型隐式转换成字符串:

using System;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string str;
            str = "" + 2 + 3.14 + true;
            Console.WriteLine(str);
        }
    }
}

值得注意的是,加号+是唯一可以用于字符串运算的算数运算符,别的*/减号-取余%都不能用于字符串。


字符串格式化

除了可以通过加号来拼接字符串之外,我们还可以使用格式化字符串的方法来拼接字符串。

语法格式如下:

string.Format(<格式化字符串>, <要填入的参数>···)

在格式字符串’…{}…'中的花括号指定位置(例如{1})来指定替换目标及要插入的参数:

例如:

using System;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = string.Format("我是{0},我喜欢{1}。", "小嗷犬", "嗷嗷嗷");
            Console.WriteLine(str);
        }
    }
}

这样也可以实现字符串的拼接。

格式化字符串后接受的参数除了是字符串外还可以是别的数据类型:

using System;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = string.Format("今年是{0}年,圆周率的近似值是{1}。", 2022, 3.1415926);
            Console.WriteLine(str);
        }
    }
}

控制台打印拼接

C# 中,在进行控制台打印的时候,我们可以使用类似于字符串格式化的拼接方式:

using System;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("我是{0},我喜欢{1}。", "小嗷犬", "嗷嗷嗷");
            Console.WriteLine("今年是{0}年,圆周率的近似值是{1}。", 2022, 3.1415926);
        }
    }
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小嗷犬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值