Char 字符数组转字符串
" Char"数据类型或字符数据类型用于存储字母,与数字和整数不同,字母和数字以整数和浮点形式存储,
字符本质上是整数类型,其大小为1字节,可打印字符为(空格),!,",#,$,%,&," ,(,),*,+,,,-,。,/,0,1,2,3,4,5,6,7,8,9,: ,;,<,=,>,?,@ ,A,a,B,b,C,c,D,d,E,e,F,f,G,g,H,h,I,i,J,j,K,k,L,l,M ,m,N,n,O,o,P,p,Q,q,R,r,S,s,T,t,U,u,V,v,W,w,X,x,Y,y ,Z,z,[,\,],^,_,`,{,|,},〜和DEL(删除)。
我们可以使用char变量来初始化
char ch2 {'a'};打印字符" a"。
char ch1 {97};打印代码97上的值。
char ch {'5'};要打印数字字符" 5"。
C++为我们提供了以下将char数组转换为字符串的技术:
使用'c_str()'和'strcpy()'函数
使用" for"循环
"while"循环,
字符串类中的 '='运算符
使用自定义功能。
使用'c_str()'和'strcpy()'函数的语法如下:
其中,c_str()将字符串的内容转换为C样式的非终止字符串。它可以直接访问内部字符串缓冲区。
我们可以使用" for"循环将字符转换为字符串,方法是-
首先,声明字符数组,然后分配数组的大小。然后,我们声明两个变量,一个是字符串类型,另一个是int类型。此后,我们可以通过为int变量分配0来使用" for"循环,其中int变量的值将小于array_size,并且每次迭代我们将int变量的值增加1、在显示字符串变量之前,我们必须在每次迭代时将值存储在字符串变量中。
代码:-
#include <iostream>
using namespace std;
int main()
{
char char_array[] = {'L','I','D',I,'H','U','O'};
int array_size = sizeof(char_array) /
sizeof(char);
string j = "";
int i;
for(i = 0; i < array_size; i++)
{
/** retrieving and merging the value of character array on position 'i'*/
j = j + char_array[i];
}
cout << j <<endl;
}
输出:
中,我们可以使用" while"循环将char转换为字符串,方法是-
首先声明字符数组,然后分配数组的大小。然后,我们声明两个变量,一个是字符串类型,另一个是值0的int类型。我们使用" while"循环在每次迭代中检查小于array_size的int变量,并在显示字符串变量之前将值存储在字符串变量中。
代码:-
#include <iostream>
using namespace std;
int main()
{
char char_array[] = {'L','I','D',I,'H','U','O'};
int array_size = sizeof(char_array) / sizeof(char);
string j = "";
int i = 0;
while(i < array_size)
{
/**retrieving and merging the value of character array on position `i`*/
j = j + char_array[i];
i++;
}
cout << j <<endl;
}
输出:
中,要使用 std :: string 构造函数将字符转换为字符串,我们只需将数组传递给字符串构造函数即可。
代码:-
#include <iostream>
using namespace std;
int main()
{
char char_array[] = {'L','I','D',I,'H','U','O'};
string j(char_array);
cout << j <<endl;
}
输出:
中,要使用'='运算符和字符串类将字符数组转换为字符串,我们必须将字符数组传递给字符串变量。
代码:-
#include <iostream>
using namespace std;
int main()
{
char char_array[] = {'L','I','D',I,'H','U','O'};
string j = char_array;
cout << j <<endl;
}
输出:
中,要使用自定义函数将字符转换为字符串,我们必须创建带有两个参数的自定义函数。在自定义函数中,我们必须声明两个变量string和integer。然后,我们使用" for"循环,其中我们将0分配给一个int变量,而int变量的大小要小于比array_size更大,并且int变量的值在每次迭代时增加一。该函数将返回字符串。对于主函数,我们声明字符数组及其大小,然后将字符数组及其大小传递给自定义函数。最后,我们打印存储自定义函数返回值的字符串变量。
代码-
#include <iostream>
using namespace std;
string charToString(char* arr_char, int arr_size)
{
int i;
string j = "";
for(i = 0; i < arr_size; i++)
{
j = j + arr_char[i];
}
return j;
}
int main() {
char char_array[] = {'L','I','D',I,'H','U','O'};
int array_size = sizeof(char_array) / sizeof(char);
string jtp = "";
jtp = charToString(char_array, array_size);
cout << jtp <<endl;
return 0;
}
输出:
将char转换为字符串的最后一种方法是使用 std :: stringstream 实现的。我们使用此函数将输入字符插入缓冲区,然后使用 std :: string 将缓冲区中的字符作为字符串。
代码-
#include <iostream>
#include <sstream>
int main()
{
char char_array[] = {'L','I','D',I,'H','U','O'};
std::string jtp;
std::stringstream strStream;
strStream << char_array;
strStream >> jtp;
std::cout << jtp;
return 0;
}
输出: