C++ string:字符串与字符串流

包含头文件:#include <string>

一、字符串常用操作

  • C++ string与C语言 char*之间的相互转换
    • str.c_str()
    • std::string()
  • 字符串与float/int之间的相互转换
  • 返回字符串长度
    • C++中的字符串std::string可以视为std::vector<char>类型,因此可以用.size()函数返回字符串的字符长度(不含'\n'结尾符号),同.length()方法。

二、字符串分割

应用场景:从txt/obj等文本文件中逐行读取数据,并按照 ,进行数据分割

方法一:使用C++字符串分割的相关函数findsubstr

适用场景:每一行字符串的格式是固定的,例如存储关键点坐标的txt文件,形如x, y格式

int idx = str.find(',');  // 获取字符的索引位置
string x_pos = str.substr(0, idx);	//  起始坐标+子串长度
string y_pos = str.substr(idx+1);

类似的函数:find_first_of, find_last_of

方法二:使用字符串流stringstream

适用场景:字符串中带有空格,以空格进行分隔

string str = " #include \"frame_warp_core.glsl\"";

std::istringstream ss(str);
ss >> token;
std::cout << "token: " << token << std::endl;  // #include
ss >> token;
std::cout << "token: " << token << std::endl;  // "frame_warp_core.glsl"
posted @ 2024-01-01 10:58  达可奈特  阅读(13)  评论(0编辑  收藏  举报