A quick way to count the number of  newlines '/n' in string of 200 chars

I am trying to establish the number of lines that a string will generate.
I can do this by counting the number of '/n' in the string. However my brute force method (shown below) is very slow.
Normally this would not be a problem on a 2800mhz Athlon (Standard) PC this takes < 1 second. However this code resides within a speed critical loop (not shown). The code shown below is a Achilles heal as far as the performance of this speed critical loop goes.
Can anyone suggest a faster way to count the number of �/n� (new lines) within a text string of around 50- 1000 chars, given that there may be 10 � 100 newline chars. Speed is a very important factor for this part of my program.
Thanks in advance
Andrew.
    int lineCount =0;
    String txt = this.getText();
    //loop throught text and count the carridge returns
    for (int i = 0; i < txt.length(); i++)
      char ch = txt.charAt(i);
      if (ch == '\n')
       lineCount ++;
    }//end forMessage was edited by:
scottie_uk
Message was edited by:
scottie_uk

Well, here is a C version. On my computer the Java version (reply 9 above) is slightly faster than C. YMMV. For stuff like this a compiler can be hard to beat even with assembler, as you need to do manual loop unrolling and method inlining which turn assembly into a maintenance nightmare.
// gcc -O6 -fomit-frame-pointer -funroll-loops -finline -o newlines.exe newlines.c
#include <stdio.h>
#include <string.h>
#if defined(__GNUC__) || defined(__unix__)
#include <time.h>
#include <sys/time.h>
#else
#include <windows.h>
#endif
#if defined(__GNUC__) || defined(__unix__)
typedef struct timeval TIMESTAMP;
void currentTime(struct timeval *time)
    gettimeofday(time, NULL);
int milliseconds(struct timeval *start, struct timeval *end)
    int usec = (end->tv_sec - start->tv_sec) * 1000000 +
     end->tv_usec - start->tv_usec;
    return (usec + 500) / 1000;
#else
typedef FILETIME TIMESTAMP;
void currentTime(FILETIME *time)
    GetSystemTimeAsFileTime(time);
int milliseconds(FILETIME *start, FILETIME *end)
    int usec = (end->dwHighDateTime - start->dwHighDateTime) * 1000000L +
     end->dwLowDateTime - start->dwLowDateTime;
    return (usec + 500) / 1000;
#endif
static int count(register char *txt)
    register int count = 0;
    register int c;
    while (c = *txt++)
     if (c == '\n')
         count++;
    return count;
static void doit(char *str)
    TIMESTAMP start, end;
    long time;
    register int n;
    int total = 0;
    currentTime(&start);
    for (n = 0; n < 1000000; n++)
     total += count(str);
    currentTime(&end);
    time = milliseconds(&start, &end);
    total *= 4;
    printf("time %ld, total %d\n", time, total);
    fflush(stdout);
int main(int argc, char **argv)
    char buf[1024];
    int n;
    for (n = 0; n < 256 / 4; n++)
     strcat(buf, "abc\n");
    for (n = 0; n < 5; n++)
     doit(buf);
}

Similar Messages

  • How i can count the number of words in a string?

    hi, i want to know how to count the number of words in a string
    e.g. java is a very powerful computer language.
    i will get 7 words.
    thanks in advance..

    Jverd, this has actually been answered, but due to an
    attack of goldie-itis, all the answers were hosed.
    The OP did get an answer, though.Yeah, I know. I just didn't know if he saw the answer before it went away.

  • Count the number of occurrence in a string

    is there any api for counting the number of occurrence in a string or should i write a method myself?
    for example. I want to count "." in "1.2.3.4.". i want to count the dot in this string.
    I am just wondering.
    Thanks in advance.

    is there any api for counting the number of
    occurrence in a string or should i write a method
    myself?The latter.

  • Which method to count the number of character in a string?

    Hi all,
    I want to know which class and method to count the number of character in a string?
    Gary

    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html

  • Fastest way to count the number of occurences of string in file

    I have an application that will process a number of records in a plain text file, and the processing takes a long time. Therefore, I'd like to first calculate the number of records in the file so that I can display a progress dialog to the user (e.g. " 1234 out of 5678 records processed"). The records are separated by the string "//" followed by a newline, so all I need to do to get the number of records is to count the number of times that '//' occurs in the file. What's the quickest way to do this? On a test file of ~1.5 Gb with ~500 000 records, grep manages under 5 seconds, whereas a naive Java approach:
    BufferedReader bout = new BufferedReader (new FileReader (sourcefile));
                   String ffline = null;
                   int lcnt = 0;
                   int searchCount = 0;
                   while ((ffline = bout.readLine()) != null) {
                        lcnt++;
                        for(int searchIndex=0;searchIndex<ffline.length();) {
                             int index=ffline.indexOf(searchFor,searchIndex);
                             if(index!=-1) {
                                  //System.out.println("Line number " + lcnt);
                                  searchCount++;
                                  searchIndex+=index+searchLength;
                             } else {
                                  break;
                   }takes about 10 times as long:
    martin@martin-laptop:~$ time grep -c '//' Desktop/moresequences.gb
    544064
    real     0m4.449s
    user     0m3.880s
    sys     0m0.544s
    martin@martin-laptop:~$ time java WordCounter Desktop/moresequences.gb
    SearchCount = 544064
    real     0m42.719s
    user     0m40.843s
    sys     0m1.232sI suspect that dealing with the file as a whole, rather than line-by-line, might be quicker, based on previous experience with Perl.

    Reading lines is very slow. If your file has single byte character encoding then use something like the KMP algorithm on an BufferedInputStream to find the byte sequence of "//\n".getBytes(). If the file has a multi-byte encoding then use the KMP algorithm on a BufferedReader to find the chars "//\n".getCharacters() .
    The basis for this can be found in reply #12 of http://forum.java.sun.com/thread.jspa?threadID=769325&messageID=4386201 .
    Edited by: sabre150 on May 2, 2008 2:10 PM

  • Is there a way to count the number of times an array moves from positive to negative?

    I have an array of values, and I need to find the number of times that the array changes signs (from positive to negative, or vice versa). In other words from a graphical standpoint, how many times a certain line crosses the x-axis. Counting the number of times the array equals zero does not help however, because the array does not always equal exactly zero when it crosses the axis (ie, the points could move from .1 to -.1).
    Thanks for you help. Feel free to email me at [email protected] I only have lv 5.1.1 so if you attach any files, they cannot be version 6.0.

    Attached is a VI showing the # of Pos and Neg numbers in an array, with 0 considered as non-Pos. It is easily modifiable to other parameters - including using the X-axis value as your compare point versus only Zero.
    This is a modified VI from LV (Separate Array.vi)
    Compare this with your other responses to find the best fit.
    Doug
    Attachments:
    arraysizesposneg.vi ‏40 KB

  • How count the number of substrings in a string

    Hi all,
    I wonder if someone can help me and point out where I'm going wrong.
    I want to count the number of substring starting with 'd' and ending with 'e' in a string supplied by a user.
    currently my code is only counting the number of 'd' and 'e' characters in the string.
        public static void main (String [] args)
             Scanner input = new Scanner (System.in);
             String mstring;// string variable that the user will enter
             int i = 0; // upstep variable
             int count = 0; // int variable to count the number of substrings
             System.out.print("Enter a string: ");
             mstring = input.nextLine();
             while (i != mstring.length())
                       if(mstring.charAt(i)=='d'){count++;}
                       else if (mstring.charAt(i)=='e'){count++;}
                       i++;
             System.out.println("The total d e substrings is " + count);
    }For example if the user enters adbedeaadffe the total number of substrings should be 5 but I'm getting 6 as the program is just counting the number of times it comes across 'd' and 'e'
    Can anyone shed some light on this for me thanks.

    Hi all I had a good few replies to this question but they seem to have been removed from the system for some reason.
    I've changed my code slightly and it works but only for one round of the guard.
                   Scanner input = new Scanner (System.in)
             String mstring;// main string variable that the user will enter
             int i = 0;  // upstep variable
             int count = 0; // int variable to count the number of substrings
         System.out.print("Enter a string: ");
             mstring = input.nextLine();
             int y =mstring.length();
             while (i != mstring.length() && y !=0)
             if (mstring.charAt(i) == 'd' && mstring.charAt(y-1)=='e'){count = count+1;}
             y--;
             i++;
             System.out.println("The total a b substrings is " + (count));The above code will only print out one substring of adbedeaadffe but that is not what I need, I need to be able to print out all of the substrings.
    Can anyone tell me where I'm going wrong.
    Thanks in advance

  • How do I count the number of *'s in a string?

    I need to count the number of * in a string of carakters. And the return the number. 0 for no *'s in the string 2 for two *'s in the string and so on.
    It's probably quite simple but I can't figure out how!

    Like this.
    james_t_dk wrote in message
    news:[email protected]..
    > I need to count the number of * in a string of carakters. And the
    > return the number. 0 for no *'s in the string 2 for two *'s in the
    > string and so on.
    >
    > It's probably quite simple but I can't figure out how!
    [Attachment Untitled 10.vi, see below]
    Attachments:
    Untitled_10.vi ‏18 KB

  • How do I count the number of occurrences of a string within a group of cells?

    Hello all, I'm trying to figure out how to count the number of times a child has completed certain tasks.  Here is a sample of the data (it is highly simplified here, but contains what I hope is needed to answer my question):
    Unnamed Table
    Objective
    John
    Ann
    Alex
    Dave
    Eric
    20a 20b 20c
    x
    20a 20b 20c
    x
    20a 20b 20c
    x
    x
    19b 20a
          x
           x
    20c 21b 22
         x
    What I am trying to do is count the number of times each child completed each objective - but I can't figure out how to go about splicing up the "objectives" fields for counting while still being able to compare them to whether or not the "child" has 'an x in the box' in that particular row.

    If I read your example correctly, John's counts should be 2 for 20a, 1 for 19b, 20b and 20c, and 0 for any other objectives listed.
    Here's an example that will work for your data set, assuming that any objective ma occur only once in each row of column A of the Main table. I've added an a to objective 22, but I think it is unnecessary, provided there is no objective 122, 221, etc.
    This uses a two step process.
    The table AUX extracts the objectives completed by each student, using the checkboxes in Main. Note that it also adds a space at the beginning and end of each string. This provides an extra character before the first objective code and after the last objective code in that row, used by the wildcard specification in the formula in the Summary table.
    Formula:
    Aux::B2: =IF(OFFSET(Data :: $A$1,ROW()-1,COLUMN()-1)," "&OFFSET(Data :: $A$1,ROW()-1,0)&" ","")
    Fill right to the last column and down to the last row of Aux.
    Summary uses COUNTIF to count the number of occurrences of each of the objectives listed in column A of that table.
    Formula:
    Summary::B2: =COUNTIF(Aux :: B,"=*"&$A2&"*")
    Fill right and down as the previous formula.
    Regards,
    Barry

  • Give me a way to count the number of entries in a  Database Table

    Hello All,
    I am writing a code to determine the number of  entries in a SAP/Custom table.
    Can you please suggest a proper approach and a good query.
    Thanks in advance.

    Hi,
    If you want to do it in a more generic way you can do the following:
    DATA: tblname(50),
          tp_rows TYPE i.
    tblname = 'MARA'.
    SELECT COUNT(*)
    FROM (tblname)
    INTO tp_rows.
    IF sy-subrc <> 0.
      CLEAR tp_rows.
    ENDIF.
    At runtime the table is being determined and in this case it's set to MARA. The value of the number of rows is in the variable tp_rows.
    Best regards,
    Guido Koopmann

  • Is there an easy way to count the number of albums I have in my library?

    Hi, there is probably a very easy way to find out how many albums I have in my iTunes library - but I haven't discovered it yet! (looking for something a bit like word count in MS Word document?)
    Powerbook G4 15 1.67   Mac OS X (10.4.3)   my first Mac - where have I been!?!

    Click on the Library icon in the source list Go Edit->Show Browser.
    This will split the library window into subwindows listing each genre, artist and album, at the top of these windows it will show the total for each of these categories.
    Apart from being the easiest way to count your albums, it's also a really useful way to view the library or any playlist. You can turn off the genre subwindow through the general preferences.
    Hope that helps!
    Sara.

  • Is there a way to count the number of chars in a formatted text box?

    I have a formatted text box in my web dynpro for comments pertaining to workflow.
    in the backend, this is mapped to a char200 field.
    is there a way to have a running counter to let the user know how many chars are left? I'm not sure if there's an event to use for that.
    thanks,
    robert.

    Hello Robert,
    There is no way to get a running total of characters typed by the user - if you really need this functionality - consider creating an Adobe Flash Island.
    There was in the last year another thread which covered pretty much the same theme - it could be worth looking at that - although you will find that the eventual solution is the same as I suggest above.

  • Count the number of rows resulting from a select statement

    Hi,
    Is there any way of counting the number of rows resulting from a select statement. i.e I have a select distinct statement and I then want to perform an IF statement on the number of rows resulting from the select statement.
    Any help appreciated
    Thanks
    Gary

    Declare
    var1 number;
    Begin
    select count(distinct column_name) into
    var1 from table_name;
    If var1 > x Then
    End IF;
    End;
    Hope I understood the problem correctly
    null

  • Count the number of rows inserted

    Hi,
    Is there a way to count the number of rows processed post DML in PL/SQL?
    For eg,
    BEGIN
    INSERT INTO TMP1
    SELECT * FROM EMP;
    a function to count the number of rows inserted into tmp1

    SQL> set serveroutput on;
    SQL> begin
    2 insert into tmp1 select * from emp;
    3 dbms_output.put_line(SQL%ROWCOUNT||' rows inserted');
    4 end;
    5 /
    15 rows inserted
    PL/SQL procedure successfully completed.

  • Counting the number of characters entered into a page item

    Is there a way to count the number of characters that are entered into a page item. I've got a field that can contain up to 20 characters. If 20 are entered I can do a = on my search, if less than that, then I have to do a wildcard search. I currently do a substr on the field to see if position 21 is null and position 20 is not null, then I have a 20 character field. Is there a more efficient way to do this and also is there a way to actually show the character count as the page item is being populated

    Hello user8014695 (name please),
    Try coding the select for your search as
    select ...
    from some_table
    where some_field like case when length(trim(:YOUR_ITEM)) = 20 then :YOUR_ITEM else :YOUR_ITEM || '%' end
    Note - I included the trim() assuming blank characters before or after shouldn't count.
    To show the character count as the item is being keyed-in, Google "javascript character count" for lots of ways to do this. To work these solutions into ApEx, check the ApEx help/documentation for incorporating JavaScript into your application - specifically the references on accessing page items using JavaScript.
    Hope this helps,
    John

Maybe you are looking for

  • Can i connect the NI 9401 to the 9162 carrier

    Hello, can I connect the NI 9401 to the USb-9162 carrier, instead of having to buy the cDAQ-9172 for just one Module ? ciao, grazie M. Petrolekas

  • Monitor tearing issue...

    Win7 PPro CC2014 and CC I am observing "tearing" on monitors* in both CC versions of PPro since upgrading to CC2014 (which required updating Nvidia Driver on install.) Geforce GTX 670 4GB 5DDR - Driver 337.88 (19/5/14) Monitors affected...*Source , P

  • Japanese Language for Sony XPeria Z1

    I have a Sony XPeria Z1 and rooted for Myanmar font and languags. But after i have rooted my phone, i can't see Japanese Language anymore. Japanese Keyboard is still working fine. How can i enable Japanese Language again ?

  • Howto pack/integrate  j2ee appllication into a portal env?

    Hi, I have some j2ee web application(war file) and i need to integrate it into portal. I dont want to use URL iView, is there any other way how to do it? Is there any possibility to call some class which extends HttpServlet(some description in portal

  • Asset retirement value

    Dear All, Four lenovo laptops was purchase in 2006 2 for rupees 143499 & the other 2 for rupees 139193 bearing same asset number, but in asset master quqntity mentioned 5 unit, At the time retireing one particular laptop by ABAON the system is pickin