从字符串转换为字符数组

编程入门 行业动态 更新时间:2024-10-25 04:14:25
本文介绍了从字符串转换为字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在从用户那里获取字符串"str". 假设用户输入了str = 123456789 我想将这些数字放在字符数组"ch1"中,而无需预定义char数组. 因此,"ch1"字符应自动具有9的大小,并且ch1 [0] = 1和ch1 [1] = 2等,依此类推....

I am taking in as a string "str" from the user. Let suppose user entered str=123456789 I want put that numbers in character array "ch1" without predefining the char array. so that "ch1" character should have the size 9 automatically and ch1[0]=1 and ch1[1]=2 and so on....

推荐答案

您可以使用 c_str [ ^ ].

如果您不需要数组具有预定义的大小,那么您应该动态分配它(记住不再需要它时,请记住删除它),例如,假设str是std::string的实例,我们有: If you don''t want an array with predefined size then you should allocate it dynamically (and remember to delete it when is no longer needed), for instance, assuming str is an instance of std::string, we have: char * ch1; ch1 = new char[str.size()+1]; // +1 makes room for string terminator strcpy(ch1, str.c_str()); //... delete [] ch1;

如果您想做类似的事情 If you would like to do something like std::string str = !23456789"; // This is invalid... char ch1[] = str; // None of the alternative below are valid. //char ch1[str.size()] = str; //char ch1[] = str.c_str(); //char ch1[str.size()] = str.c_str();

在C ++中,您不能做类似的事情. C样式数组必须具有在编译时确定的大小,并且无法通过代码中定义的C样式字符串以外的其他字符串初始化此类数组. 如果您需要修改内容,这是一个更好的选择.如果不是,则只需使用字符串运算符[]或c_str()的结果.

In C++, you cannot do something like that. C style array must have a size determined at compile time and there is no way to initialise such an array from a string other than a C-style string defined in code. Here is a much better alternative if you need to modify the content. If not, then simply use string operator [] or the result of c_str().

std::string str = "123456789"; std::vector<char> ch1(str.begin(), str.end()); // You can know use ch1 almost like an array...

更多推荐

从字符串转换为字符数组

本文发布于:2023-11-04 05:40:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557097.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字符串   转换为   字符

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!