c++ string转换为数组,示例代码
时间: 2023-06-02 20:04:32 浏览: 119
可以使用以下代码将c string转换为数组:
```
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[] = "Hello, World!";
int n = strlen(str);
char char_array[n+1];
strcpy(char_array, str);
for(int i=0; i<n; i++)
{
cout << char_array[i] << " ";
}
return 0;
}
```
在此示例中,我们使用strlen()函数获取c string的长度,然后定义一个与字符串长度相等的字符数组char_array。接下来,我们使用strcpy()函数将c string复制到char_array中。最后,我们使用一个循环遍历数组并打印每个元素。
相关问题
c++ string类型转换为数组
将string类型转换为数组可以使用string的成员函数c_str(),该函数返回一个指向字符数组的指针,即将string类型转换为C风格的字符串。然后可以使用strcpy()函数将C风格字符串复制到一个字符数组中。以下是示例代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main() {
string str = "hello world";
char arr[20];
strcpy(arr, str.c_str());
cout << "str: " << str << endl;
cout << "arr: " << arr << endl;
return 0;
}
```
输出:
```
str: hello world
arr: hello world
```
c++ string逗号分隔转数组
你可以使用 `std::stringstream` 和 `std::getline` 将逗号分隔的字符串转换为数组。下面是一个示例代码:
```c++
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main() {
std::string str = "1,2,3,4,5";
std::vector<int> nums;
std::stringstream ss(str);
std::string token;
while (std::getline(ss, token, ',')) {
nums.push_back(std::stoi(token));
}
for (int num : nums) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
```
输出结果为:
```
1 2 3 4 5
```
在上面的代码中,我们先定义了一个字符串 `str`,它包含了逗号分隔的数字。然后我们定义了一个 `std::vector<int>` 类型的数组 `nums`,用来存储转换后的数字。接着,我们使用 `std::stringstream` 将字符串 `str` 传入,并使用 `std::getline` 函数按照逗号分隔符将字符串分割成多个子串,存储在 `token` 变量中。最后,我们将 `token` 转换为 `int` 类型,并将其添加到数组 `nums` 中。
最后,我们遍历数组 `nums` 并输出每个元素的值。
阅读全文
相关推荐
















