Replace the text numbers string in a txt file using C++.. Help Me..

Read a Document and replace the text numbers in a txt file using c++..
For ex: 
Before Document: 
hai hello my daily salary is two thousand and five and your salary is five billion. my age is 
twenty-five. 
After Document: 
hai hello my daily salary is # and your salary is #. my age is #. 
All the text numbers and i put the # symbol.. 
I am trying this code: 
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
ifstream myfile_in ("input.txt");
ofstream myfile_out ("output.txt");
string line;
void find_and_replace( string &source, string find, string replace ) {
size_t j;
for ( ; (j = source.find( find )) != string::npos ; ) {
source.replace( j, find.length(), replace );
myfile_out << source <<endl;
cout << source << endl;
int main () {
if (myfile_in.is_open())
int i = 0,j;
//string strcomma ;
// string strspace ;
while (! myfile_in.eof() )
getline (myfile_in,line);
string strcomma= "two";
string strspace = "#";
find_and_replace( line , strcomma , strspace );
i++;
myfile_in.close();
else cout << "Unable to open file(s) ";
system("PAUSE");
return 0;
Please help me.. Give me the correct code..

Open the file as a RandomAccessFile. Check its length. Declare a byte array as big as its length and do a single read to get the file into RAM.
Is this a simple text file (bytes)? No problem. If it's really 16-bit chars, use java.nio to first wrap the byte array as a ByteBuffer and then view the ByteBuffer as a CharBuffer.
Then you're ready for search/replace. Do it as you would in any other language. Be sure to use System.arraycopy() to shove your bytes right (replace bigger than search) or left (replace smaller than search).
When done, a single write() to the RandomAccessFile will put it all back. As you search/replace, keep track of size. If the final file is smaller than the original, use a setLength() to the new size to avoid extraneous data at the end.

Similar Messages

  • How do i search for a string in a txt file using java??

    How do i search for a string in a txt file using java??
    could you please help thanks
    J

    Regular expressinos work just fine, especially when
    searching for patterns. But they seem to be impying
    it's a specific group of characters they're looking
    for, and indexOf() is much faster than a regex.If he's reading from a file, the I/O time will likely swamp any performance hit that regex introduces. I think contains() (or indexOf() if he's not on 5.0 yet) is preferable to regex just because it's simpler. (And in the case of contains(), the name makes for a very clear, direct mapping between your intent and the code that realizes it.)

  • How to retrieve IndividualStrings from a txt file using String Tokenizer.

    hello can any one help me to retrieve the individual strings from a txt file using string tokenizer or some thing like that.
    the data in my txt file looks like this way.
    Data1;
    abc; cder; efu; frg;
    abc1; cder2; efu3; frg4;
    Data2
    sdfabc; sdfcder; hvhefu; fgfrg;
    uhfhabc; gffjcder; yugefu; hhfufrg;
    Data3
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    i need to read the data as an individual strings and i need to pass those values to diffarent labels,the dat in Data3 i have to read those values and add to an table datamodel as 6 columns and rows depends on the data.
    i try to retrieve data using buffered reader and inputstream reader,but only the way i am retrieving data as an big string of entire line ,i tried with stringtokenizer but some how i was failed to retrive the data in a way i want,any help would be appreciated.
    Regards,

    Hmmm... looks like the file format isn't even very consistent... why the semicolon after Data1 but not after Data2 or Data3??
    Your algorithm is reading character-by-character, and most of the time it's easier to let a StringTokenizer or StreamTokenizer do the work of lexical analysis and let you focus on the parsing.
    I am also going to assume your format is very rigid. E.g. section Data1 will ALWAYS come before section Data2, which will come before section Data3, etc... and you might even make the assumption there can never be a Data4, 5, 6, etc... (this is why its nice to have some exact specification, like a grammar, so you know exactly what is and is not allowed.) I will also assume that the section names will always be the same, namely "DataX" where X is a decimal digit.
    I tend to like to use StreamTokenizer for this sort of thing, but the additional power and flexibility it gives comes at the price of a steeper learning curve (and it's a little buggy too). So I will ignore this class and focus on StringTokenizer.
    I would suggest something like this general framework:
    //make a BufferedReader up here...
    do
      String line = myBufferedReader.readLine();
      if (line!=null && line.trim().length()>0)
        line = line.trim();
        //do some processing on the line
    while (line!=null);So what processing to do inside the if statement?
    Well, you can recognize the DataX lines easily enough - just do something like a line.startsWith("Data") and check that the last char is a digit... you can even ignore the digit if you know the sections come in a certain order (simplifying assumptions can simplify the code).
    Once you figure out which section you're in, you can parse the succeeding lines appropriately. You might instantiate a StringTokenizer, i.e. StringTokenizer strtok = new StringTokenizer(line, ";, "); and then read out the tokens into some Collection, based on the section #. E.g.
    strtok = new StringTokenizer(line, ";, ");
    if (sectionNo==0)
      //read the tokens into the Labels1 collection
    else if (sectionNo==1)
      //read the tokens into the Labels2 collection
    else //sectionNo must be 2
      //create a new line in your table model and populate it with the token values...
    }I don't think the delimiters are necessary if you are using end-of-line's as delimiters (which is implicit in the fact that you are reading the text out line-by-line). So the original file format you listed looks fine (except you might want to get rid of that rogue semicolon).
    Good luck.

  • Replacing the text

    Hello All,
    I need your help regarding replacing the text with some other text. I am trying to replace the text '\\' with '\'. But i am not able to get the correct result.
    I am having string value like   '\\Computername\Path\comp_name\\domain\\location' i want to replace the text '\\' with '\' only for 2nd and 3rd occurance.
    Replace \\domain\\ with \domain\ I have tried with below query...
    SELECT REGEXP_REPLACE('\\Computername\Path\comp_name\\domain\\location' ,
           '(\\){2,}', '\')
           AS Expression
      FROM dual;i am getting the below result for above query.
      \Computername\Path\comp_name\domain\location But i want the output like below..
    \\Computername\Path\comp_name\domain\location I am using Oracke 11g vesion.
    Please help me on this .
    Thanks a lot for your help.

    Hi,
    sunitha2010 wrote:
    ... small doubt--Is there any difference between these two queries?Let's call this Query 1:
    SELECT  REGEXP_REPLACE ( str
                     , '\\\\'    -- 2 backslashes, escaped.  See note below
                     , 1 + INSTR ( str
                     )     AS expression
    FROM    table_x
    ;and Let's call the query below Query 2:
    select
    REGEXP_REPLACE
    ('\\Computername\Path\comp_name\\domain\\location', '\\\\', '\\',2 )
    as Expression
    from
    dual
    ;Yes, there is a difference.
    Query 1 leaves the first occurrence of '&#92;&#92;' intact, regardless of where that is in the string.
    Query 2 ignores the 1st character, but otherwise changes all occurrences of '&#92;\' into a single '\'.
    You'll see the difference if you add anything to the very beginning of the test string, for example
    'X\\Computername\Path\comp_name\\domain\\location'I mentioned this in my first message:
    Frank Kulash wrote:
    ... I assume the 1st occurrence won't always be at the beginning of the string...If the first occrence always is at the beginning of the string, then you don't need regualr expressions at all. You can say:
    SELECT  SUBSTR (str, 1, 1)
         || REPLACE ( SUBSTR (str, 2)
              )     AS expression
    FROM    table_x;This will be more efficient than regular expressions.

  • PE 13 crashes due to incompatible video driver detected. Running on Win 7 SP1 with ATI 540v video card/driver.  Deleting bad driver file in adobe program data does not fix the problem,  it simply replaces the text file and crashes again.  My video driver

    PE 13 crashes due to incompatible video driver detected. Running on Win 7 SP1 with ATI 540v video card/driver.  Deleting bad driver file in adobe program data does not fix the problem,  it simply replaces the text file and crashes again.  My video driver is just fine.  Any help out there?

    rb
    Your video card driver may be fine for something, but just not compatible with Premiere Elements 13/13.1.
    For those with the display card error, the answers include
    a. assure your video card/graphics card driver version is up to date according to the web site of the manufacturer of the card -
    if necessary consider a driver roll back.
    b. determine in Device Manager/Display Adapters if the computer is using 2 cards instead of 1
    c. delete the BadDrivers.txt file
    the rationale for that deletion is found in post 10 of the following older post...principle applies to 13 as well as 9.
    Re: Premiere Elements 9 Tryout Serious Display Problem
    Have you looked for computer ATI card settings that might be more compatible with Premiere Elements 13/13.1?
    When is the program crashing - just opening a new project or rather crashing if editing a particular video format at the Timeline level?
    ATR

  • The text numbers 08 will not show up in mountain lion

    the text numbers 08 will not show up in mountain lion. i did a software update after i installed and it did not solve the problem.
    Is anyone else having this problem or know how to fix it?

    dj,
    Restart the computer.
    Repair Permissions in Disk Utility.
    Check fonts and clear out bad ones in Font Book.
    Try in another User Account.
    Any luck?
    Jerry

  • To replace the Text like "History,Back" with Images in Page Title bar

    Hi All,
    My requirement is to change the Text like "History,Back Forward" Texts with the Images in the Page Title bar.Under theme editor I dont have an option to replace with Image.
    I checked with the com.sap.portal.navigation.pagetoolbar.par file.I am not getting exactly where to replace the Text with Images.
    Please let me know if I am referring to the correct par file and where to make changes.
    Regards
    Akshaya
    Edited by: Akshaya Bhat on Jun 9, 2009 2:58 PM

    Hi,
    It depends if the WDJ application has made another navigation.
    History saves any navigations made by the user (TLN/DTN,etc) or navigation done by applications in code (wdDoNavigate, EPCM.doNavigate).
    So it can go back to previous view , or previous iview the user was at...
    Regards,
    Tal.

  • How to read and write a string into a txt.file

    Hi, I am now using BEA Workshop for Weblogic Platform version10. I am using J2EE is my programming language. The problem I encounter is as the above title; how to read and write a string into a txt.file with a specific root directory? Do you have any sample codes to reference?
    I hope someone can answer my question as soon as possible
    Thank you very much.

    Accessing the file system directly from a web app is a bad idea for several reasons. See http://weblogs.java.net/blog/simongbrown/archive/2003/10/file_access_in.html for a great discussion of the topic.
    On Weblogic there seems to be two ways to access files. First, use a File T3 connector from the console. Second, use java.net.URL with the file: protocol. The T3File object has been deprecated and suggests:
    Deprecated in WebLogic Server 6.1. Use java.net.URL.openConnection() instead.
    Edited by: m0smith on Mar 12, 2008 5:18 PM

  • How to calculate the number of vowels from a txt file. Pls give me a hand!!

    Guys! How do i calculate the number of vowels from a txt file? I have to create a program to count the number of words, sentence, and vowels. So far I had managed to count the number of words. Now I need help on counting sentence and vowels! Pls give me a hand guys!

    I first have to read from the file not the string.I
    know how to read from a file. Now the problem ishow
    to compare a character from a txt file!You fail to understand, that you have read the data
    from the file into a string. Now loop over all
    characters in the string. Forget about the file.
    KajOr forget the scanners just as others have told you. Just read the file character by character using a FileReader.
    Kaj

  • Saveindg a String in a .txt-File

    Hello,
    I want to save a String to a .txt-File, that is placed in a certain directory.
    How can I Do that?
    Tank you very much!
    Greeting from cologne!
    Marcel

          * Write text to a file.
         * @param text Text to write.
          * @param fileName Name of file to write to.
          * @throws IOException on error.
         static public void writeText(String text, String fileName) throws IOException {
            if (fileName != null && text != null) {
                BufferedWriter bw = null;
                try {
                    bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "ISO-8859-1"));
                    bw.write(text, 0, text.length());
                } finally {
                    if (bw != null) { try { bw.close(); } catch (IOException ioe) { ioe.printStackTrace(System.err); }}
            }//else: input unavailable
        }//writeText()Please read D:\docs\JavaTutorial\essential\io\index.html

  • Someone at the AT&T store told me to backup the phone numbers in my phone on Itunes.  Please help.

    Someone at the AT&T store told me to backup the phone numbers in my phone on Itunes.  Please help.

    http://support.apple.com/kb/ht1766
    http://support.apple.com/kb/HT1296
    Regards.

  • Count the number of lines in a txt file

    I need to count the number of lines in a txt file, but I can't do it using readLine(). This is because the txt file is double spaced. readLine() returns null even if it is not the end of the file. thanks for the help

    I need to count the number of lines in a txt file,
    but I can't do it using readLine(). Then just compare each single byte or char to the newline (code 10).
    This is because the txt file is double spaced. readLine() returns
    null even if it is not the end of the file.Errm what? What do you mean by "double spaced"? Method readLine() should only return null if there's nothing more to read.

  • I made a beautiful invitation for my sons graduation in pages it has 1 photo on the front and 5 photos on the back. When I try to export it to my work pc the text is not supported and it looks terrible. Help!

    I made a beautiful invitation for my sons graduation in pages it has 1 photo on the front and 5 photos on the back. When I try to export it to my work pc the text is not supported and it looks terrible. Help!

    How did you transfer it to the PC?
    Not good to export as a Word .doc/x, better to:
    Menu > Export > PDF
    Peter

  • Loading the data from a packed decimal format file using a sql*loader.

    Hi ,
    In one of the project i'm working here i have to load the data into oracle table from a file using a Sql*loader but the problem is the data file is in the packed decimal format so please let me know if there is any way to do this....I search a lot regarding this ..If anybody faced such type of problem ,then let me the steps to solve this.
    Thanks in advance ,
    Narasingarao.

    declare
    f utl_file.file_type;
    s1 varchar2(200);
    s2 varchar2(200);
    s3 varchar2(200);
    c number := 0;
    begin
    f := utl_file.fopen('TRY','sample1.txt','R');
    utl_file.get_line(f,s1);
    utl_file.get_line(f,s2);
    utl_file.get_line(f,s3);
    insert into sampletable (a,b,c) values (s1,s2,s3);
    c := c + 1;
    utl_file.fclose(f);
    exception
    when NO_DATA_FOUND then
    if utl_file.is_open(f) then utl_file.fclose(f); ens if;
    dbms_output.put_line('No. of rows inserted : ' || c);
    end;SY.

  • How to find and replace the text present in the url

    I have a column of type NCLOB with some text having url's in between as shown below:
    ========================================================================
    This text is for testign purpose.This text is for testign purpose.
    <A PL/SQL <U PL/SQL </U> </A>
    Thsi text is also for testign purpose.This text is for testign purpose.
    <A http://forums.oracle.com> <U oracle metalink> </U> </A>
    This text is for testign purpose.This text is for testign purpose.This text is for testign purpose.This text is for testign purpose.This text is for testign purpose.This text is for testign purpose.This text is for testign purpose.This text is for testign purpose.
    ========================================================================
    Requirement:
    ========
    Requirement is to implement the find and replace functionality.
    I just need to check whether the search text is present in the url or not?
    Suppose if search for orcale.com, since its part of the url so the search should be successful otherwise search should be unsuccessful.
    Here I can give you the hint like, always the url lies between the anchor tags *(<A </A>).*
    Tahnks in Advance.

    I had I think a similiar question the other day thay I Frank and Michaels answered for me.
    not sure if I totally have what you want but.
    WITH t
            AS (SELECT '<A PL/SQL <U PL/SQL Thsi text is also for testign purpose.This text is for testign purpose.
    <A http://forums.oracle.com> This text is for testign purpose.This text is for testign purpose.This text is for testign purpose.This text is for testign purpose.This text is for testign purpose.This text is for testign purpose.This text is for testign purpose.This text is for testign purpose.
                          txt
                  FROM DUAL)
    SELECT REGEXP_SUBSTR (REGEXP_REPLACE (txt, '(.*<A)|(</A>.*)'), 'oracle.com')
      FROM tthe first part the regexp replace part gets the text between a start and end point you mentioned that would be <A and </A>
    the regexp substr just looks for the phrase oracle.com in the text between those two points.
    Edited by: pollywog on Oct 6, 2010 8:26 AM

Maybe you are looking for

  • AVCHD and Mac Pro 8 Core

    Hey is there anyone on the forum editing AVCHD footage in FCS 2 on there Mac Pro 8 Core 2.8 GHZ.Would be great to hear how users machines are performing with this new format. thanks Alex

  • Setting for J2EE server do not exist

    Hi, I have prepared a web service from a FM. I can't test it from the WSADMIN since this system is not integrated to a J2EE server. So I get the error message "Setting for J2EE server do not exist" I am able to generate the WSDL file from Tcode WSADM

  • Music Screen not showing

    when i select a song, the album art or blue time track is not showing. all i see is blank. the artist,songs,etc names are showed but not the actual album art or blue track of the song. is there a wayto restore?

  • Cuando abro una pestaña nueva, me la abre con otra página de inicio que no he preestablecido

    Cuando abro una pestaña, me la abre siempre con una página de inicio que no he preestablecido. ¿Como puedo cambiarla?, ya que en herramientas/opciones/general, aparece la página que quiero para la página de inicio, pero no así para las pestañas nueva

  • My iPod touch can't send through I message and call from FaceTime

    I can't send messages in iMessage and all from FaceTime, I already verified my address and registered but I can't send, I hope you can help, please reply immediately..