如何在c ++中将少数bacis字符组合成一个字符串

时间:2015-11-11 18:43:04

标签: c++ string char

正如一个话题所说。我尝试将几个字符(从数组)组合成一个字符串。 我试过了

lib

但它没有用。

4 个答案:

答案 0 :(得分:1)

char test[]={'A'};
char testt[]={'a'};
string testtt="";
testtt+=test[0];
testtt+=testt[0];

答案 1 :(得分:0)

您可以使用带有char *,length的构造函数。

#include<iostream>
#include<string>

int main(){


char test[]={'A'};
char testt[]={'a','w'};
std::string testtt= std::string(&test[0], 1) + std::string(&testt[1],1);/
std::cout<<testtt<<std::endl;
return 0;
}

或带有范围的构造函数:

std::string testtt= std::string(&test[0], &test[1]) + std::string(&testt[0],&testt[1]);

答案 2 :(得分:0)

它会起作用;)

#include <sstream>

string toStr(char* tab, int length)
{
    stringstream ss;
    for (int i=0 ; i<length; i++)
        ss << tab[i];
    return ss.str();
}

答案 3 :(得分:0)

如果您查看类字符串,您会发现它不会使复制构造函数超载以获取一个字符参数。 你可能认为你实现了自己的包含字符串对象的类:

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;


class MyStr
{
    public:
        MyStr(char c){ itsString = c;}
        string GetStr()const {return itsString;}

    private:
        string itsString;
};



int main(int argc, char* argv[])
{

char test[]={'A'};
char testt[]={'a'};
MyStr testtt = test[0] + testt[0];

cout << testtt.GetStr() << endl;


cout << endl << endl << endl;
return 0;
}

这个程序运行并且编译器从不抱怨但是结果不会像你想象的那样:它不会是“Aa”而只是:'Ê'因为实际上是上面的语句:string testtt = test [0 ] + testt [0];相当于写:cout&lt;&lt; (char)('A'+'a'); 这意味着将两个字符相加,结果是整数ASCII值,那么这个值将再次转换回charater,因为你真的是在追逐字符串(char);这将导致(162的特征)