删除std::String类型字符串首尾空格

本文提供了C++中去除字符串左右两侧空白字符的方法。通过使用`std::string`成员函数结合`std::ctype_base::space`,实现了左、右及两端空白字符的有效移除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <string> 

// 删除左侧空格
std::string &trimleft(std::string &str) 
{ 
	str.erase(0, str.find_first_not_of(std::ctype_base::space));
	return str;
} 

// 删除右侧空格
std::string &trimright(std::string &str) 
{ 
	str.erase(str.find_last_not_of(std::ctype_base::space) + 1);
	return str;
} 

// 删除首尾空格
std::string &trim(std::string &str) 
{ 
	return trimleft(trimright(str)); 
} 

#include <iostream> #include <fstream> #include <istream> #include <sstream> #include <streambuf> #include <vector> #include <string> #include <stdlib.h> void printCsv(std::vector<std::string> line_data) { std::cout << line_data[0] // << atof(line_data[1].c_str()) // << atof(line_data[2].c_str()) << line_data[1] << line_data[2] << line_data[3] << std::endl; } int main() { std::ifstream csv_data("C:\\Users\\17718\\Desktop\\newtest.csv", std::ios::in); std::string line; if (!csv_data.is_open()) { std::cout << "Error: opening file fail" << std::endl; exit(1); } std::vector<std::string> words; //声明一个字符串向量 std::string word; // ------------读取数据----------------- // 读取标题行 std::getline(csv_data, line); std::istringstream sin; // 按行读取数据 while (std::getline(csv_data, line)) { // 清空vector,只存当前行的数据 words.clear(); sin.clear(); sin.str(line); while (std::getline(sin, word, ',')) //将字符串流sin中的字符读到field字符串中,以逗号为分隔符 { std::cout << word << std::endl; words.push_back(word); //将每一格中的数据逐个push } printCsv(words); } csv_data.close(); std::ofstream outFile; outFile.open("C:\\Users\\17718\\Desktop\\newtest.csv", std::ios::out | std::ios::trunc); // 写入标题行 outFile << "name" << ',' << "income" << ',' << "expenditure" << ',' << "addr" << std::endl; // ********写入两行数据********* // 写入字符串(数字) outFile << "zhangsan" << ',' << "3000" << ',' << "1200" << ',' << "中国 陕西省" << std::endl; // 写入浮点数(转为字符串) outFile << "lisi" << ',' << std::to_string(2032.1) << ',' << std::to_string(789.2) << ',' << "中国 北京市" << std::endl; outFile.close(); return 0; }
最新发布
06-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值