Advertisement
Guest User

C++ string replacer

a guest
May 22nd, 2012
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. #include <cstdlib>
  2. #include <iostream>
  3. #include <fstream>
  4.  
  5. using namespace std;
  6.  
  7. string *fromStrings=new string[1000];
  8. string *toStrings=new string[1000];
  9. int members;
  10. /**
  11.  * Loads a language into the arrays.
  12.  * The syntax of the file should be old:new
  13.  * @param filename - The path to the file
  14.  */
  15. void loadLanguage(string filename,int lines)
  16. {  
  17.     string buffer;
  18.     members=lines;
  19.    
  20.     ifstream file(filename.c_str());
  21.     for(int index=0; index<lines; index++)
  22.     {
  23.     getline(file,buffer);
  24.    
  25.     if(buffer.find(":")!=-1){
  26.     toStrings[index]=buffer.substr(0,buffer.find(":"));
  27.     fromStrings[index]=buffer.substr(buffer.find(":"),buffer.length());
  28.    }
  29.     }
  30. }
  31. //!Not my work
  32. void replaceAll(std::string& str,  std::string& from,  std::string& to) {
  33.     size_t start_pos = 0;
  34.     while((start_pos = str.find(from, start_pos)) < std::string::npos) {
  35.         str.replace(start_pos, from.length(), to);
  36.         start_pos += to.length();
  37.     }
  38. }
  39.  
  40. /**
  41.  * Compiles the language set up by loadLangauge.
  42.  * It really just places it in a text file in C++.
  43.  * @param fileName - Where to find the file
  44.  * @param lines    - How many lines the file has.
  45.  */
  46. void compile(string fileName,int lines){
  47.  
  48.     string line[lines];
  49.     ifstream reader(fileName.c_str());
  50.  
  51.     for(int index=0; index<lines; index++)
  52.         getline(reader, line[index]);
  53.    
  54.     for(int index=0; index<lines; index++)
  55.     {
  56.         for(int secInd=0; secInd<members; secInd++)
  57.         {
  58.             replaceAll(line[index],toStrings[secInd],fromStrings[secInd]);
  59.         }
  60.         cout << line[index]<<endl;
  61.     }
  62.     reader.close();
  63. }
  64. int main(){
  65.     loadLanguage("/home/nate/langdefines",10);
  66.    
  67.     compile("/home/nate/code",3);
  68.    
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement