21xrx.com
2024-09-19 08:58:21 Thursday
登录
文章检索 我的文章 写文章
如何将C++字符串转换为数组
2023-06-27 03:29:47 深夜i     --     --
C++ 字符串 转换 数组

C++字符串和数组在程序设计中都有着重要的作用。但有时候我们需要将一个字符串转换为数组,例如要对每个字符进行操作或者通过数组下标来访问字符串中的某个字符。下面列出了几种将C++字符串转换为数组的方法:

1. 使用std::vector

std::vector是C++标准库中的一个类,它可以用来实现动态数组。使用std::vector将C++字符串转换为数组的方法如下:


#include <iostream>

#include <string>

#include <vector>

int main() {

  std::string str = "hello world";

  std::vector<char> arr(str.begin(), str.end());

  for (auto c : arr)

    std::cout << c << " ";

  

  return 0;

}

2. 使用c_str()

C++字符串的成员函数c_str()可以返回一个指向字符数组的指针。使用c_str()将C++字符串转换为数组的方法如下:


#include <iostream>

#include <string>

#include <cstring>

int main() {

  std::string str = "hello world";

  const char* arr = str.c_str();

  for (int i = 0; i < str.length(); i++) {

    std::cout << arr[i] << " ";

  }

  return 0;

}

3. 使用std::copy()

C++标准库中的std::copy()可以将一个区间的元素复制到另一个区间中。使用std::copy()将C++字符串转换为数组的方法如下:


#include <iostream>

#include <string>

#include <algorithm>

int main() {

  std::string str = "hello world";

  char arr[20];

  std::copy(str.begin(), str.end(), arr);

  for (int i = 0; i < str.length(); i++) {

    std::cout << arr[i] << " ";

  }

  return 0;

}

无论采用哪种方法,将C++字符串转换为数组都是很常见的程序设计需求。开发者可以根据需要选取最合适的方法。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复