C++ 一些常用方法的总结

本文介绍了一种去除字符串前后空格的方法,并展示了如何从文本文件中读取键值对数据,通过使用自定义的trim函数和标准模板库(map)来处理文本数据。

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

我初学,莫笑。呵呵!

1.去除字符串前后空格:

string  trim( string   & str)
{
    
if  (str.empty()) 
    {
        
return  str;
    }
    str.erase(
0 ,str.find_first_not_of( "   " ));
    str.erase(str.find_last_not_of(
"   " +   1 );
    
return  str;
}

当然去除前端空格,或者去除末尾空格都已经明了。

2.文本文件读取,文件内容键值对 ,以‘=’分隔:

     string  strtmp;
    ifstream fs(
" Test.txt " );
    map
< string , string >   map_temp;
    
string ::size_type index  =   string ::npos;

    
while (getline(fs,strtmp, ' \n ' ))
    {
        index 
=  strtmp.find( " = " );
        map_temp[trim(strtmp.substr(
0 ,index - 1 ))]  =  trim(strtmp.substr( ++ index));
    }
    map
< string , string >  ::iterator it  =  map_temp.begin();

    
for (; it  !=  map_temp.end(); it ++ )
    {
        cout 
<<  it -> first  <<   " = "   <<  it -> second  <<  endl;
    }

注意:
string s = "aa=" ; 其中 ‘=’索引为2,s.substr(0,1) 返回的将是"aa".




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值