最近没啥可写的 这里写下做的STL小练习 作为记录
去除指定字符串中的空格
获取文件名并根据名字创建临时文件,以TMP后缀结尾,已经为TMP后缀结尾文件则创建以XXX后缀结尾文件
读取一行输入内容 并将单词翻转打印
// 1111.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <string> #include <iostream> #include <algorithm> using namespace std; string strArray[5] = {"prog.dat","mydir","hello.","oops.tmp","end.dat"}; string TrimSpace(string str) { string::size_type i; while( (i = str.find(" ")) != string::npos ) { str.replace(i,1,""); } string::iterator newEnd = remove(str.begin(),str.end(),‘ ‘); str.erase(newEnd,str.end()); return str; } void ReversPrintWordInLine() { const string delims(" \t,.;"); string line; while(getline(cin,line)) { string::size_type begIdx,endIdx; begIdx = line.find_first_not_of(delims); while(begIdx != string::npos) { endIdx = line.find_first_of(delims,begIdx); if(endIdx == string::npos) { endIdx = line.length(); } for(int i = endIdx-1;i >= static_cast<int>(begIdx);--i) { cout << line[i]; } cout << ‘ ‘; begIdx = line.find_first_not_of(delims,endIdx); } cout << endl; } } void CreateTmpFilename() { string filename,basename,extname,tmpname; const string suffix("tmp"); for(int i = 0;i < 5;++i) { string::size_type idx = strArray[i].find("."); if(idx == string::npos) { tmpname = strArray[i]+"."+suffix; }else { basename = strArray[i].substr(0,idx); extname = strArray[i].substr(idx+1); if(extname.empty()) { tmpname = strArray[i]; tmpname += suffix; }else if(extname == suffix) { tmpname = strArray[i]; tmpname.replace(idx+1,extname.size(),"xxx"); }else { tmpname = strArray[i]; tmpname.replace(idx+1,suffix.size(),suffix); } } cout << strArray[i] << " ==> " << tmpname << endl; } cout << endl; } int _tmain(int argc, _TCHAR* argv[]) { string str = TrimSpace(" sdfsf sdfs sdf "); cout << "remove space " << str << endl << endl; CreateTmpFilename(); ReversPrintWordInLine(); return 0; }
stl string 小练习
时间: 2024-10-06 01:53:35