C++ 将字符串和数组拼接起来

参考:https://blog.csdn.net/PROGRAM_anywhere/article/details/63720261

java中的String类,连接字符和数字仅需一个+号,但c++中的string类,+号只能用于连接两个string类型的字符,如需连接字符和数字,则需自己写程序来实现

参考博文中给出了四种方式,分别利用了不同的c++函数和特性

//c风格

//使用sprintf()函数,将多个不同类型的变量输入到char型数组中

//sprintf()函数中第一个参数就是指向要写入的那个字符串的指针,剩下的和printf()一样

#include <stdio.h>

void test() {

    char *s = "doing";

    int a = 52;

    float b = .1314;

    char *buf = new char[strlen(s) + sizeof(a) + 1];

    sprintf(buf, %s%d%.4f, s, a, b);

    printf(%s\n, buf);

}


//半c半c++风格

//itoa()函数可将数字转化为字符串(char类型数组),再用+号将原字符与数字字符串连接起来

//itoa()函数有三个参数,1、要转换的数字;2、要写入转换结果的目标字符串;3、转换数字时所用的基数(2-36进制)

//itoa()函数并不是标准的C函数,它是Windows特有的,若要写跨平台的程序,需用sprintf()函数

//_itoa_s()函数,c++11版本后,如VS2013版本以后对该函数进行了修改,并定义了更加安全稳定的接口_itoa_s(),使用方法同itoa()函数一样

#include <stdlib.h>;//或

#include <cstdlib>;

#include <iostream>

using namespace std;

void test1() {

    string s = "dong";
    int a = 520;
    char *buf = new char[10];
    _itoa_s(a, buf, 10);     
    cout << s + buf << " | ";
    _itoa_s(a, buf, 16);
    cout << s + buf << endl;

}


//纯c++风格

//字符串流,ostringstream , 由ostream派生而来,提供写string的功能

//ostringstream的一个常见用法是,在多种数据类型之间实现转换或格式化

#include <iostream>

#include <sstream>

void test2()
{
    string s = "陈明东";
    int a = 52;
    double b = .1314;
    ostringstream oss;
    oss << s << a << b;//将s、a、b写入oss流中
    cout << oss.str() << endl;//打印oss中存储的string类型对象

}


//C++11新特性

//std::to_string()是C++标准(2011年)的最新版本引入的全局函数,可将其他类型转换为string

#include <iostream>
#include <string>

void test3()

{
    int a = 520;
    float b = 5.20;
    string str = "dong";
    string res = str + to_string(a);
    cout << res << endl;
    res = str + to_string(b);
    res.resize(8);
    cout << res << endl;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值