跳转至

字符串

前置知识

输入输出

目标

C风格字符串(C-string),char s[N] 字符数组 C++字符串,string 类

C风格字符串

char s[110]; // s 是数组的名称,也当成一个指针使用
int len = strlen(s);

char s1[] = "aaa";
char s2[] = "bbb";
int p = strcmp(s1, s2); // 相等是0,小于是负数,大于是正数

strcat(s1, s2); // s1后面拼接上s2

strcpy(s1, s2); // s2复制给s1,s1存的东西变成和s2一样

int s[110];
memset(s, 0, sizeof s);  // 全都赋值成0
memset(s, 0x3f, sizeof s); // 全都赋值成0x3f3f3f3f,0x开头的表示16进制数

char s1[] = "abc";
char s2[] = "bcd";
memcpy(s1, s2, sizeof s1); // 把s2的值赋值给s1

string

string s1, s2;
s1 += s2;  s1.append(s2); 拼接操作

if (s1 == s2) 判断相等的操作
s1 < s2直接比较大小字典序
s.size()

s1 = s.substr(pos, len);  截取子串
cout << s.substr(2) << '\n';     //截取子串,是位置2开始往后所有
cout << s.substr(2, 3) << '\n';  //从位置2开始,截取三位

s.insert(pos. s1); 插入字符串

int p = s.find('A');  or s.find("abc")  查找子串会返回第一次出现的位置如果没找到返回string::npos
int p = s.find('A', pos); 从哪个位置开始往后找

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博客