Finding the number of occurance in a string

Hi Can someone tell me if there is a function to tell me how many times a string occurs in another string for example how many times does
"cat"
appear in
"cat dog catcat dogdog cat cat"

Praveen_Forum wrote:
Try in the similar lines
String name = "cat dog catcat dogdog cat cat";
char pattern = 'c';
int occurs = 0;
for(int i = 0; i < name.length(); i++) {
char next = name.charAt(i);
if(next == pattern) {
occurs++;
System.out.println("Occurs " + occurs + " time(s)");
for a string:
String name = "cat dog catcat dogdog cat cat";
String toFind = "cat";
int occurs = 0;
for(int i = 0; i < name.length()-toFind.length()+1; i++)
    if (name.substring(i, i+toFind.length()).equals(toFind))
       occurs++;
System.out.println(occurs);

Similar Messages

  • How to find the number of occurance of a string in text field of Infopath form?

    Hi All,
    In Infopath text field, How to find the number of occurrence of a particular string in that field?
    Thanks in advance!

    You can check to see if it contains a string once by using the contains function, but there isn't a very clean way to do what you want. If you wanted to guess at the maximum number of occurrences, then you could:
    Box A has your initial. Set Box B to do a concat of string-before and string-after of Box A where it copies Box A minus the string we're looking for. Then we have Box C that does the same thing to Box B. Repeat as many times as you see necessary.
    Example:
    String: "1"
    Box A - "123451234512345"
    Box B - "23451234512345"
    Box C - "2345234512345"
    Box D - "234523452345"
    etc.
    We then have a field that has nested ifs looking backwards from Z -> A looking for a non-blank. Based on that, we return the number of occurrences. Again, this isn't clean, but it will work if you think there's a predefinable maximum.
    Andy Wessendorf SharePoint Developer II | Rackspace [email protected]

  • How to find the number of occurence of a string

    String str="The AR tech seeks experienced candidates in java,jsp. The candidates should have atleast 1 year of experience in the specified skills.";
    here i need to find the number of occurence of the string "experience".
    how to find it out?

    String str="The AR tech seeks experienced candidates in java,jsp. The candidates should have atleast 1 year of experience in the specified skills.";
    String findStr = "experience";
    int count = 0;
    int index = 0;
    while(index != -1) {
    index = str.indexOf(findStr, (count == 0 ? 0 : index + findStr.length()));
    if(index != -1) {
    count++;

  • Find the number of occurances in string, to break up output

    I have a string that might contain 12345, or 12335,6789, or 123435,6789,9999, etc...unlimited
    When I display, the string is very long, lengthwise. So I want to break it up and display one on top of another.
    I started to use the Find function to location the postion of the comma, then used Mid function to get the first value, the repeat similar process to get the second and third values. This seems to work and the display is the way I want it.
    Howver, I know I have three values inside the string, so I can adjust accordinly. What if I do not know how many values there are ? How would I separate to get the desired output ?
    This is my code so far, based on three values :
    <cfset pos1 = Find(",","#qry.carrierTracking#")>
    <cfif pos1 is not 0>
    <cfset carrier1 = #mid(qry.carrierTracking,1,(pos1 - 1))#>
    <cfset carrier2 = #mid(qry.carrierTracking,(pos1 + 1),50)#>
    </cfif>
    <cfset pos2 = Find(",","#carrier2#")>
    <cfif pos2 is not 0>
    <cfset carrier2A = #mid(carrier2,1,(pos2 - 1))#>
    <cfset carrier3 = #mid(carrier2,(pos2 + 1),50)#>
    </cfif>
    <cfif pos1 is not 0 and pos2 is not 0>
    <cfoutput>#carrier1#<br>#carrier2A#<br>#carrier3#<br></cfoutput>
    </cfif>

    Wouldn't you just replace all the commas with a comma followed by a <br /> ?
    Adam

  • Find the Number of times a '¯'character appears in a string.

    Hi,
    In my staging table I am having data like below
    ABL¯ABL¯0¯0¯ABL¯ ¯ ¯ ¯ ¯ ¯ ¯ ¯ ¯ 
    ABL¯ABQ¯480¯825¯DLS¯AMA¯ABQ¯ ¯ ¯ ¯ ¯ ¯ ¯ 
    ABL¯ACD¯808¯1255¯DLS¯ELP¯TCS¯PHX¯ACD¯ ¯ ¯ ¯ ¯ 
    ABL¯ADE¯1256¯471¯DLS¯AMA¯ABQ¯LSV¯ADE¯ ¯ ¯ ¯ ¯ 
    ABL¯AFT¯1140¯1744¯DLS¯LAX¯FON¯AFT¯ ¯ ¯ ¯ ¯ ¯ 
    ABL¯AHM¯1178¯1637¯DLS¯LAX¯AHM¯ ¯ ¯ ¯ ¯ ¯ ¯ 
    ABL¯ALB¯1769¯1825¯DLS¯WIL¯ALB¯ ¯ ¯ ¯ ¯ ¯ ¯ 
    ABL¯ALE¯1041¯1150¯DLS¯ALE¯ ¯ ¯ ¯ ¯ ¯ ¯ ¯ ¯
    Now I want to find the Number of times a '¯'character appears in a string.
    I should get output 14
    thanks & regards,
    Vipin Jha
    Thankx &amp; regards, Vipin jha MCP

    Hi Vipin,
    You can try below sql code also
    code:-  len(data)-len(replace(data,'¯','')) -(len(data)-len(replace(data,' ','')))
    select data,len(data)-len(replace(data,'¯','')) -(len(data)-len(replace(data,' ',''))) CountofCharacter from
    select 'ABL¯ABL¯0¯0¯ABL¯ ¯ ¯ ¯ ¯ ¯ ¯ ¯ ¯ ' data
    UNION
    SELECT 'ABL¯ABQ¯480¯825¯DLS¯AMA¯ABQ¯ ¯ ¯ ¯ ¯ ¯ ¯ '
    UNION
    SELECT 'ABL¯ACD¯808¯1255¯DLS¯ELP¯TCS¯PHX¯ACD¯ ¯ ¯ ¯ ¯ '
    UNION
    SELECT 'ABL¯ADE¯1256¯471¯DLS¯AMA¯ABQ¯LSV¯ADE¯ ¯ ¯ ¯ ¯ '
    UNION
    SELECT 'ABL¯AFT¯1140¯1744¯DLS¯LAX¯FON¯AFT¯ ¯ ¯ ¯ ¯ ¯ '
    UNION
    SELECT 'ABL¯AHM¯1178¯1637¯DLS¯LAX¯AHM¯ ¯ ¯ ¯ ¯ ¯ ¯ '
    UNION
    SELECT 'ABL¯ALB¯1769¯1825¯DLS¯WIL¯ALB¯ ¯ ¯ ¯ ¯ ¯ ¯ '
    UNION
    SELECT 'ABL¯ALE¯1041¯1150¯DLS¯ALE¯ ¯ ¯ ¯ ¯ ¯ ¯ ¯ ¯'
    ) t
    Thanks
    Prasad

  • How to find the number of records per months  in cube

    Hi,
      how to find the number of records per months for my all cubes?
      Can i use the ListCube transaction to find totl number f records per cube monthwise ?
    Jimmy

    Hi,
    Here is a program to generate no of records and list of ODS and Cubes in Active version.Schedule this program in background and create a cube to load this information and schedule to the data from the file generated by the program. Schedule this all per you requirement.
    1.Copy the code into your Z<programname> from Se38.
    2.change the FILENAME in CALL FUNCTION 'GUI_DOWNLOAD' in the program to the location from where you can pick the information to load data to cube(eg Application server).
    3.Save program.
    4.Schedule the program in background as required
    5.Create cube with infoobjects to hold no of records and Infoprovider name
    6.Load this cube based on event after the program job is done.
    Hence you can report on this cube to see no of records in  CUBE or ODS in your box.
    Please find the code below.
    Cheers,
    Kavitha Kamesh.
    types: begin of itabs ,
          tabname type dd02l-tabname,
          end of itabs.
    data: itab type itabs occurs 0 with header line.
    data: counter type i.
    data: begin of itab1 occurs 0,
    tabname type dd02l-tabname,
    counter type i,
    end of itab1.
    DATA: ITABTABNAME TYPE STRING.
    DATA: LENGTH TYPE I.
    DATA: OBJECT(30).
    data: str(6) type c.
    select  tabname from dd02l into table itab where ( tabname LIKE  '/BIC/F%' or tabname LIKE  '/BIC/A%00' )
    and TABCLASS = 'TRANSP' and AS4LOCAL = 'A'.
    loop at itab.
      select count(*) from (itab-tabname) into counter.
      str = itab-tabname.
      if str = '/BIC/F'.
    LENGTH  = STRLEN( ITAB-TABNAME ).
      SHIFT  itab-tabname BY 6 PLACES LEFT.
    ELSEIf  str = '/BIC/A'.
      SHIFT  itab-tabname BY 6 PLACES LEFT.
      LENGTH  = STRLEN( ITAB-TABNAME ).
    LENGTH = LENGTH - 2.
    endif.
      itab1-tabname = itab-tabname(LENGTH).
      append itab1.
      itab1-counter = counter.
      clear itab-tabname.
      clear:  COUNTER.
    endloop.
    *********** itab1
    loop at itab1.
    write:/ itab1-tabname, itab1-counter.
    endloop.
    CALL FUNCTION 'GUI_DOWNLOAD'
      EXPORTING
    *   BIN_FILESIZE                    =
        FILENAME                        = 'c:records.xls'
        FILETYPE                        = 'ASC'
    *   APPEND                          = ' '
        WRITE_FIELD_SEPARATOR           = ','
    *   HEADER                          = '00'
    *   TRUNC_TRAILING_BLANKS           = ' '
    *   WRITE_LF                        = 'X'
    *   COL_SELECT                      = ' '
    *   COL_SELECT_MASK                 = ' '
    *   DAT_MODE                        = ' '
    *   CONFIRM_OVERWRITE               = ' '
    *   NO_AUTH_CHECK                   = ' '
    *   CODEPAGE                        = ' '
    *   IGNORE_CERR                     = ABAP_TRUE
    *   REPLACEMENT                     = '#'
    *   WRITE_BOM                       = ' '
    *   TRUNC_TRAILING_BLANKS_EOL       = 'X'
    *   WK1_N_FORMAT                    = ' '
    *   WK1_N_SIZE                      = ' '
    *   WK1_T_FORMAT                    = ' '
    *   WK1_T_SIZE                      = ' '
    * IMPORTING
    *   FILELENGTH                      =
      TABLES
        DATA_TAB                        = itab1
    *   FIELDNAMES                      =
    * EXCEPTIONS
    *   FILE_WRITE_ERROR                = 1
    *   NO_BATCH                        = 2
    *   GUI_REFUSE_FILETRANSFER         = 3
    *   INVALID_TYPE                    = 4
    *   NO_AUTHORITY                    = 5
    *   UNKNOWN_ERROR                   = 6
    *   HEADER_NOT_ALLOWED              = 7
    *   SEPARATOR_NOT_ALLOWED           = 8
    *   FILESIZE_NOT_ALLOWED            = 9
    *   HEADER_TOO_LONG                 = 10
    *   DP_ERROR_CREATE                 = 11
    *   DP_ERROR_SEND                   = 12
    *   DP_ERROR_WRITE                  = 13
    *   UNKNOWN_DP_ERROR                = 14
    *   ACCESS_DENIED                   = 15
    *   DP_OUT_OF_MEMORY                = 16
    *   DISK_FULL                       = 17
    *   DP_TIMEOUT                      = 18
    *   FILE_NOT_FOUND                  = 19
    *   DATAPROVIDER_EXCEPTION          = 20
    *   CONTROL_FLUSH_ERROR             = 21
    *   OTHERS                          = 22
    IF SY-SUBRC <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.

  • How to find the number of fetched lines from select statement

    Hi Experts,
    Can you tell me how to find the number of fetched lines from select statements..
    and one more thing is can you tell me how to check the written select statement or written statement is correct or not????
    Thanks in advance
    santosh

    Hi,
    Look for the system field SY_TABIX. That will contain the number of records which have been put into an internal table through a select statement.
    For ex:
    data: itab type mara occurs 0 with header line.
    Select * from mara into table itab.
    Write: Sy-tabix.
    This will give you the number of entries that has been selected.
    I am not sure what you mean by the second question. If you can let me know what you need then we might have a solution.
    Hope this helps,
    Sudhi
    Message was edited by:
            Sudhindra Chandrashekar

  • How to find the number of references created for a given  object ??

    How to find the number of references created for a given object in a big application environment.
    That means, if i give any object name (of my application) as input, then how can i find the[b] number of references created for that particular object ??

    Please do not post the same question multiple times.
    As for your original question, there is no direct way to do it.
    Especially not the way you phrased it,
    since objects don't have "names".
    Applications also don't have "names".
    They have classes and instances.
    Also, there are 2 related issues, and I'm not sure which one is the one you asked.
    #1. Finding the number of references to the same object.
    Eg.
    Map<String,String> a = new HashMap<String,String>();
    Map<String,String> b = new HashMap<String,String>();
    Map<String,String> c = a;In this case, there are only 2 objects.
    The first object has (at least) 2 references pointing to it.
    The second object has (at least) 1 reference pointing to it.
    (There may be more, if the HashMap library keeps
    references to these things, or if the HashMap object has
    some internal cyclic references...)
    If you're asking this, then it can't be done.
    It's an active research topic in universities
    and software research labs, called "alias analysis".
    Type it in google, and you'll see people are working hard
    and having little success so far.
    #2. Finding the number of instances created from a class.
    In this case, what you have to do is to add a counter to
    the constructor of the class. Every time an object is constructed,
    you increment the counter. Like this:
       class MyClass
           public static int counter = 0;
           public MyClass( )  { counter++; }
        // Then later in your program, you can do this:
        MyClass a = new MyClass();
        MyClass b = new MyClass();
        System.out.println(MyClass.counter); // It should show 2Note: you won't be able to do this to every class in the system.
    For every class you care about, you have to modify its constructor.
    Also: when an object is deleted, you won't always know it
    (and thus you won't always be able to decrement the counter).
    Finalizers cannot always work (read Joshua Bloch's
    "Effective Java" book if you don't believe me), but basically
    (1) finalizers will not always be called, and
    (2) finalizers can sometimes cause objects to not be deleted,
    and thus the JVM will run out of memory and crash

  • How do you find the number of lines in a file?

    I need to count how many lines there are in a file, I am using a BufferedReader to read in the data, but how can I find the number of lines?
    Thanks

    That depends. How do you define a line? Is it a specific number of
    characters, a String that's terminated by a newline character or some
    combination thereof?

  • Finding the number of Non-Blank Line in a File

    Does anyone know the command or how to find the number of non-blank lines in a text file? I have the program already reading characters, words, and total lines.
              BufferedReader FileIn = new BufferedReader( new FileReader( selectedFile ) );
                   Scanner scanWords = new Scanner (selectedFile);
                             String thisToken = "";
                             int numWords = 0;
                             while (scanWords.hasNext())
                             thisToken = scanWords.next();
                             numWords++;
         System.out.println("Total number of words: " + numWords);
         Scanner scanLines = new Scanner (selectedFile).useDelimiter("\n");
                             String thisToken2 = "";
                             int numLines = 0;
                             while (scanLines.hasNext())
                             thisToken2 = scanLines.next();
                             numLines++;
         System.out.println("Total number of lines: " + numLines);
         Scanner scanChars = new Scanner (selectedFile).useDelimiter("");
                             String thisToken3 = "";
                             int numChars = 0;
                             while (scanChars.hasNext())
                             thisToken2 = scanChars.next();
                             numChars++;
         System.out.println("Total number of characters: " + numChars);
                   FileIn.close();
              }

    Use BufferedReader#readLine() instead. Read the file once and process each line once.

  • Udf to count the number of occurances

    Hello All
    I am trying to write an UDF which can count the number of occurances of charecter ' in a string and fives the result as number of occurances - 3 . For example if the char ' is present 20 times in a string , I want the result to be 17.
    Could you help me in creating this UDF please, I am a beginner to Java.
    Thank you

    Hi Sreeni ,
    I tried you code , but it has some compilation errors ,
    The cod ei used is
      //write your code here
    int count = 0;
    String str;
    for(int i=0; i=input.strlength();i++)
    if (input = '\'')
    count = count + 1;
    count = count - 3;
    str = integer.toString(count);
    return str;
    Just as you suggested ,
    for it I got these errors
    incompatible types
    found : int required: boolean
    for(int i=0; i=input.str.length();i++)
    cannot resolve symbol
    symbol : variable str
    location: class java.lang.String
    for(int i=0; i=input.str.length();i++)
    incompatible types
    found : java.lang.String
    required: boolean if (input = '\'')
    cannot resolve symbol
    symbol : variable integer
    location: class com.sap.xi.tf._MMPOFileToPayload_
    str = integer.toString(count);
    cheers

  • How to find the number of data items in a file written with ArryToFile function?

    I have written an array of number in 2 column groups to a file using the LabWindows/CVI function ArrayToFile...Now if I want to read the file with FileToArray Function then how do I know the number of items in the file. during the write time I know how many array items to write. but suppose I want the file to read at some later time then How to find the number of items in the file,So that I can read the exact number and present it. Thanks to all
    If you are young work to Learn, not to earn.
    Solved!
    Go to Solution.

    What about:
    OpenFile ( your file );
    cnt = 0;
    while ((br = ReadLine ( ... )) != -2) {
    if (br == -1) {
    // I/O error: handle it!
    break;
    cnt++;
    CloseFile ( ... );
    There are some ways to improve performance of this code, but if you are not reading thousands of lines it's quite fast.
    After this part you can dimension the array to pass to FileToArray... unless you want to read it yourself since you already have it open!
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?

  • How to find the number of entries in a master data table

    Hi Experts,
    I am trying to find the entries in 0CUSTOMER master data.
    BW>LISTCUBE>Data target: 0CUSTOMER and selected the fields that I need.
    I would like to know how to find the "number of entrees". I tried to run the SUM for a count field, but it is taking forever as there are huge number of records .

    Hi Dev,
    Go to the change/display mode of the info object (0CUSTOMER) in your case. Go to the Master data/Text tab. Here you will find the master data tables according to your settings (P orQ or X or Y). Double click on the table name and it will take you to the SE11 display. From there, you can check the number of records as you do in any transparent table.
    Hope this helps.
    Thanks and Regards
    Subray Hegde

  • How to find the number of links in a website

    hi every body
    can any one clear my doubt
    my doubt is that
    in a website how to find the number of links the hole website contains
    is there any navigation tool to find that
    plz help me yar
    i am waiting for the reply

    If you're talking about commercial sites (sites you don't have the source code for) I'm not sure.
    If you want to count the links in site that you have the source code for, it should be relatively easy to write a Java application to do it. All you really need to do is have a list of the files you want to count links in, read each file line by line and check for the existance of the <a> tag in each line. Anywhere their is an <a> tag there is a link.
    Hope this helps.

  • How to find the number of times method being called.....

    hi,
    can any one pls tell me how to find the number of times the method being called......herez the example....
    Refrence ref = new Refrence();
    for(int i = 0;i < arr.length; i++){
    if(somecondition){
    ref.getMethod();
    here i want to know how many times the getMethod() is calling...Is there any method to do this.. i have seen StrackTraceElement class..but not sure about that....pls tell me the solution....

    can any one pls tell me how to find the number of times the method being called......
    herez the example.... http://www.catb.org/~esr/faqs/smart-questions.html#writewell
    How To Ask Questions The Smart Way
    Eric Steven Raymond
    Rick Moen
    Write in clear, grammatical, correctly-spelled language
    We've found by experience that people who are careless and sloppy writers are usually also careless and sloppy at thinking and coding (often enough to bet on, anyway). Answering questions for careless and sloppy thinkers is not rewarding; we'd rather spend our time elsewhere.
    So expressing your question clearly and well is important. If you can't be bothered to do that, we can't be bothered to pay attention. Spend the extra effort to polish your language. It doesn't have to be stiff or formal ? in fact, hacker culture values informal, slangy and humorous language used with precision. But it has to be precise; there has to be some indication that you're thinking and paying attention.
    Spell, punctuate, and capitalize correctly. Don't confuse "its" with "it's", "loose" with "lose", or "discrete" with "discreet". Don't TYPE IN ALL CAPS; this is read as shouting and considered rude. (All-smalls is only slightly less annoying, as it's difficult to read. Alan Cox can get away with it, but you can't.)
    More generally, if you write like a semi-literate b o o b you will very likely be ignored. So don't use instant-messaging shortcuts. Spelling "you" as "u" makes you look like a semi-literate b o o b to save two entire keystrokes.

Maybe you are looking for

  • BPC 10.1 - dump in unified model when I try to open System Reports

    Hi, we use BPC 10.1 unified and every time when try to use "System Reports" it dumps. I can select e.g. BPF Activity Report and Templates -> Template Verions -> Instances and finally "Display Report" but there is no result besides the endless loading

  • How do i migrate all my imovie projects from one computer to another

    how do i migrate all my imovie projects from one computer to another

  • Help with transferring contacts and messages

    Hi there - I would be grateful if someone could help me . I need to transfer my contacts and messages from my iPhone 4 to iPhone 5- Is there an easy way of doing this Manu thanks

  • Loading History Data

    Hi All. I have some data loaded in BW flow from Nov 13 to Till date.Its a daily load.Now the client wants the data before Nov. 13 also.One month data has above 2 crore records.Its an FIGL Load.As its a daily load,i have a small window of time to load

  • Error : while Importing SAP Objects in ESR.

    I am getting error, while importing SAP object in a scenario in ESR. What can be the issue ? as we have configured all the beckend settings & sldcheck is also OK. Also, we are using proxy scenarios are working fine on system. The details are as below