Hello获取字符串的最后N个字符需要帮助: 有这样的一行:
PutPixel(x + N, y + N, 0, 0, 0); // N = 1 - 1000
并希望得到最后9个符号,其中" 0,0,0);" ,我有50k行的那些,每行有不同的数字,我想找到每一行0,0,0);在最后并从数组中删除它,首先我必须找到它们
我已经尝试了line[N].substr(0,-9);
但是这样做不起作用,我也试过了line[N].find("0, 0, 0);");
但这只是游戏我的长期谎言" 4294967295"
完整代码:
const string file = "putpixel.txt";
const int maxlines = 60000;
int main()
{
string lines[maxlines];
fileRead(file,lines);
deleteBlack(lines);
cout << lines[0].find("0, 0, 0);");
return 0;
}
void fileRead(const string fn,string line[]){
int index = 0;
ifstream fin(fn.c_str());
while(!fin.eof()){
getline(fin,line[index],';');
index++;
}
fin.close();
}
答案 0 :(得分:1)
此代码从文件加载文本并搜索
" 0, 0, 0"
并使用
" "
searchresult = stringFile.find(" 0, 0, 0")
和
substr( searchresult + search_string.length() , stringFile.length() )
它会一直这样做,直到searchresult = -1
。如果是,它会将更改的结果写回文件。
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
int main(){
int searchresult=1;
ifstream inFile;
// load file into string
inFile.open("putpixel.txt");
stringstream strStream;
strStream << inFile.rdbuf();
string stringFile = strStream.str();
inFile.close();
cout<<"\nBefore replace \n";
cout<<""<<stringFile<<" \n";
// initialize search string and replace string
string search_string = " 0, 0, 0";
string replace_string = " ";
// while searchresult is still greater than zero then keep searching
while ( searchresult > 0 ){
searchresult = stringFile.find(search_string);
// if searchresult is greater than zero then keep doing this
if(searchresult >= 0){
string tmpstring = stringFile.substr(0,searchresult);
tmpstring += replace_string;
tmpstring += stringFile.substr(searchresult+search_string.length(), stringFile.length());
stringFile = tmpstring;
}
}
// update file after removing
ofstream outFile("putpixel.txt");
outFile << stringFile;
outFile.close();
cout<<"\nAfter replace \n";
cout<<""<<stringFile<<" \n";
cout<<"\nPress ANY key to close.\n\n";
cin.ignore(); cin.get();
return 0;
}
putpixel.txt
之前的输出:
PutPixel(x + N, y + N, 0, 0, 0);
PutPixel(x + N, y + N, 0, 0, 0);
PutPixel(x + N, y + N, 0, 0, 0);
PutPixel(x + N, y + N, 0, 0, 0);
putpixel.txt
之后的输出:
PutPixel(x + N, y + N, );
PutPixel(x + N, y + N, );
PutPixel(x + N, y + N, );
PutPixel(x + N, y + N, );