跳转至

其他操作

string 与 字符数组 互相转换

char*  char str[] 类型可以直接转换为 string 类型
string str = chstr 或者是 string str = arstr
// 字符数组 转 string
char arr[10];
strcpy(arr, "hello, world");
string s = arr;

string 提供一个方法可以直接返回字符串的首指针地址 string.c_str()比如 string str = "Hi !" 转换为 char* 类型
const char* mystr = str.c_str()在这里注意要加上const
// string 转 字符数组
char arr[10];
string s = "hello, world";
strcpy(arr, s.c_str());

to_string 转换成 string

// to_string example
#include <iostream>   // std::cout
#include <string>     // std::string, std::to_string

int main ()
{
  std::string pi = "pi is " + std::to_string(3.1415926);
  std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number";
  std::cout << pi << '\n';
  std::cout << perfect << '\n';
  return 0;
}

// pi is 3.141593
// 28 is a perfect number

int double 转换成 string

// string 转换成 int
string s = "1234";
int x = stoi(s);

// C 风格字符串(C-string)转换成 double
scanf("%s", s);
double x = atof(s);

// Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int.
int x = atoi(s);

参考

C风格字符串和string类型的相互转换_c字符串转string-CSDN博客