21xrx.com
2024-06-03 01:53:20 Monday
登录
文章检索 我的文章 写文章
C++中字符串转数组的方法
2023-07-10 00:09:23 深夜i     --     --
C++ 字符串 数组 转换方法

在C++编程中,有时需要将字符串转换为数组来进行一些操作。下面介绍几种常用的字符串转数组的方法。

1.使用strcpy()函数

strcpy()函数是C库中提供的一个函数,用于将一个字符串复制到另一个字符串中。可以使用该函数将字符串转换为数组。

下面是一段示例代码:


#include <cstring>

#include <iostream>

using namespace std;

int main() {

  string str = "Hello, world!";

  char arr[str.size() + 1];

  strcpy(arr, str.c_str());

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

    cout << arr[i];

  }

  return 0;

}

2.使用stringstream类

stringstream类是C++标准库中的一个类,可以将字符串按照指定的分隔符分割为多个字符串。可以使用该类将一个字符串转换为数组。

下面是一段示例代码:


#include <iostream>

#include <sstream>

#include <string>

using namespace std;

int main() {

  string str = "1 2 3 4 5";

  int arr[5];

  stringstream ss(str);

  for (int i = 0; i < 5; i++) {

    ss >> arr[i];

  }

  for (int i = 0; i < 5; i++) {

    cout << arr[i] << endl;

  }

  return 0;

}

通过上述两种方法,可以将字符串转换为数组,并对其进行操作。在实际的编程中,开发者可以根据具体的需求选择适合的方法。

  
  

评论区

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