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

Similar Messages

  • 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.

  • 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.

  • 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);
    }

  • 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

  • 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

  • Count the number of char in a string

    hi gurs
    for example ,there is a string "abcdaa", i want a sql that shows the number of 'a' in the string ,in this case,the sql should return 3 cause there are three 'a' in the string, how to write this sql
    thank you very much.

    As an alternative or if you're using 9i or below you can use this:
    SQL> with t as (
      2  select 'abcdaa' x from dual union all
      3  select 'AbcdaA' x from dual)
      4  -- end of sample data
      5  SELECT x, length(x) - length(replace(x, 'a', '')) count_chr
      6    FROM t;
    X       COUNT_CHR
    abcdaa          3
    AbcdaA          1
    SQL>

  • Counting the number of digits in a field

    Hello friends,
    does anyone know of any function module by which we can count the number of digits in a field.
    Say i have a priority field which is numc2, and the the user fills in a 5 digit number in it, i was to calculate this and raise an error if the number of digits is more than 2.
    Thanks in advance.
    charu.

    data : text(10),
          len type i.
    text = <your variable which user is passing>
    len = strlen( text ).
    if len gt 2.
    message 'Length incresed' type 'E'.
    endif.
    regards
    shiba dutta

  • How to count the number of characters

    Dear All,
                Can anyone tell me a Function Code or sample code to count the number of charactes in a text.
    Regards,
    Vijay

    hi
    <b>use the inbuilt function strlen</b>
    Number of characters in arg; blanks at the end of data objects with a fixed length are not counted, although they are counted in type string data objects. If you use a non-Unicode double-byte code, a character that occupies 2 bytes is counted twice.
    <b>example</b>
    data: v_len type i,
    v_str type string value 'gggugik'.
    v_len = strlen( v_str ).
    write:/ v_len.
    Regards,
    ravish
    <b>plz reward points if helpful</b>

  • Get number of character within a String by number of pixels

    How can i get the number of character within a String
    by a width value...
    for example..
    i have a String = "1234567890abcdefghi.........."
    and when i give the width "10"
    i will get the String "12".
    or the number of charcter..
    or somthingggggggggggggggg
    please help..
    Shay

    i solved this...
    by doing somthing similar..
    i made a for loop on all character
    and evrey time i am get a sub string from the 0 till the loop index..
    and i am chashing the last string
    so when a sub width is greater the the requested width
    i am returning the lst cashed result
    thanks.. all..

  • How to count the number of test ABAP Unit test methods

    I need to count the number of test methods of a class.   Has anybody done this before?   For example, if I have a class that has 3 methods and I wrote 6 abap unit test methods for it.   I can count the number of methods using cl_abap_classdescr=>describe_by_name (which gave me 3 from my example) but I could not find the function module to count the number of test methods (which should give me 6 in my example).
    I appreciate your reply.

    This call does thew trick.  I just had to make sure the prog name that I pass has "CP" from the 30th pos for it return the result.   Here is thew subroutine that I use:
    form get_test_method_count using     query_class
                               changing  test_method_count.
      data: l_progname type progname.
      l_progname = query_class.
      l_progname+30 = 'CP'.  "needed so the following method will recognize this as a class
      data: l_result type if_aunit_prog_info_types=>ty_t_testclasses.
      try.
          call method cl_aunit_prog_info=>get_tests_of_program
            exporting
              progname = l_progname
            receiving
              result   = l_result.
          if l_result is not initial.
            data: result_rec like line of l_result.
            loop at l_result into result_rec.
              test_method_count = lines( result_rec-methods ).
            endloop.
          endif.
        catch cx_root.
      endtry.
    endform.

  • To count the number of occurences of a character

    Hi All,
    Is there a particular function to count the number of occurences of a particular character in a string...?
    Let me know if u know the same.
    Thanx and regards
    Akshat

    A method with a test driver:
    public class a {
         public static void main(String args[]) {
              System.out.println(howmany(args[0],args[1].charAt(0)));
         public static int howmany(String what,char c) {
              String regexp = "" + c;
              String s=null;
              try     {
                   s=what.replaceAll(regexp,"");
              catch (Exception e) {          
                    regexp = "\\" + c;
                   s=what.replaceAll(regexp,"");
              return what.length() - s.length();
    }

  • Java Program+To count the number of lines in a method excluding comments???

    Hi friends
    can u plz help me out, the java program is counting the number of lines in a method excluding comments.
    The first thing is how to identify a method, then there can be an inner method inside the parent method,
    Please friends its urgent
    Bye
    Sandy

    There's no such thing as an inner method in Java. You can either write the code yourself to parse Java source, or maybe something like ANTLR can do it.

  • How to count the number of occurences of a character

    hi
    wat command is used to count the number of occurences of a charcter in a line?
    i have to count the number of '.' in a line

    FIND
    Searches for patterns.
    Syntax
    FIND <p> IN [SECTION OFFSET <off> LENGTH <len> OF] <text>
                [IGNORING CASE|RESPECTING CASE]
                [IN BYTE MODE|IN CHARACTER MODE]
                [MATCH OFFSET <o>] [MATCH LENGTH <l>].
    The system searches the field <text> for the pattern <p>. The SECTION OFFSET <off> LENGTH <len> OF addition tells the system to search only from the <off> position in the length <len>. IGNORING CASE or RESPECTING CASE (default) specifies whether the search is to be case-sensitive. In Unicode programs, you must specify whether the statement is a character or byte operation, using the IN BYTE MODE or IN CHARACTER MODE (default) additions. The MATCH OFFSET and MATCH LENGTH additions set the offset of the first occurrence and length of the search string in the fields <p> and <l>.

Maybe you are looking for