Find the nth occurrence of a string in a string

Hi,
I'm wondering if there is a method like indexOf, but finds the nth occurrence of a string
public static int occurrence(java.lang.String str,
                             java.lang.String toFind,
                             int occurrence)Cheers
Jonny

phdk wrote:
calypso was refering to promes pseudo code.What is promes? I don't understand the word. Sorry!
I put the global variable 'count' now in the method occurence
public static int occurence(String str, String toFind, int occurence){
        int origLength = str.length();
        int count = 0;
        while(str.length()>0){
            str = contains(str, toFind, count);
               if(count == occurence){
                int length = str.length();;
                int actualPos = origLength-(length+1);
                return actualPos;
               count++;
        return -1;
public static String contains(String str, String toFind, int count){
        int occurence = str.indexOf(toFind);
        if(occurence != -1 ){
             count = count+1;
            return str.substring(occurence+1,str.length());
        }else{
            return "";
  }The output is 1 position to high.
I still don't get which part of the code to replace with this pseudo code: s'.indexOf('toFind', 'index'+1)
Sorry for being dimwitted!
Thanks
jonny

Similar Messages

  • Here's how to find the right word in a string

    I needed to find the rightmost word in a string. I didn't find a simple formula in these forums, but I now have one, so I wanted to share it. Hope you find it useful.
    Assuming that the string is in cell A1, the following will return the rightmost word in the string:
    RIGHT(A1,LEN(A1)-FIND("*",SUBSTITUTE(A1," ","*",LEN(A1)-LEN(SUBSTITUTE(A1," ","")))))

    I found the problem. Whatever character was being used in the substitution was parsed out by the forum parser. I replaced it with "œ" (option q on my keyboard).
    =RIGHT(A1,LEN(A1)-FIND("œ",SUBSTITUTE(A1," ","œ",LEN(A1)-LEN(SUBSTITUTE(A1," ","")))))
    Still needs an error check for a single-word "sentence" and to remove the trailing period but it does seem to work. Pretty slick.
    Message was edited by: Badunit
    I see below that the problem was fixed by the OP.
    Message was edited by: Badunit

  • How we can find the last character in a string(Urgent Plz!)

    Gurus!
    How we can find the last character in a string.
    e.g i have a string say "Str" with value "10-01".
    Now i want to find the last character in "Str" i.e "ONE=1".
    i am using Oracle developer 6i with Oracle 8i(1.7).
    Plz help!
    Many thanks!

    Use the substr() and length() functions -
    x := '10-01';
    y := substr(x, length(x));

  • Searching for the nth occurrence of a substring in a string

    I need to search for the 63rd occurrence of a substring <i4> and replace it with <string>. Is there an easy way to do this?
    Edited by: sarcasteak on Jun 16, 2009 11:52 AM

    nevermind I got it, if anyone was curious
    int z = 0;
                   while(z<63)
                        index = index2+3;
                        index2 = result.indexOf("<param>", index);
                        resultTest = result.substring(index2);
                        //System.out.println(index2 + " :" + resultTest );
                        z++;
                   String originalSubstring = (result.substring(index2);
                   String modifiedSubstring = "";
                   modifiedSubstring = originalSubstring.replaceFirst("<i4>","<string>" );
                   modifiedSubstring = modifiedSubstring.replaceFirst("</i4>","</string>" );
                   String fixedString= result.replace(originalSubstring, modifiedSubstring);
                   System.out.println(fixedString);Edited by: sarcasteak on Jun 16, 2009 12:32 PM

  • How to match the nth word in a string?

    Hi, when I have a string like
    "AA BBBB CCC DDDDDD EEE FF"
    all words are of the form \w+
    and I'd like to match the nth word, for example the third would be "CCC",
    how can I establish this with just one regular expression?
    Some annotations:
    This is done with Java 1.4, but tools like the string tokenizer are not
    possible (restrictions of the application) We're limited to one regular expression!
    In Perl, one would do it this way:
    This would be the regular expression:
    "[\w+\s+\w+\s+](w+)"
    and with the help of $1, you might match the first paranthesis.
    As I said before, this is no solution here, because we're limited to one
    regular expression
    Another idea for Java Regex would be to define a positive lookahead, like (?<=\w+\s+\w+\s+), but as the width of it is variable, it is not allowed!
    Thanks for your help,
    Heiko Kubidsky

    well, i did another test class
    import java.util.regex.*;
    public class NthMatch {
    public static void main(String[] args) {
      Pattern p = Pattern.compile(
        "(?:\\w+\\s+){" + args[1] + "}(\\w+)(?:\\s.*)?");
      Matcher m = p.matcher(args[0]);
      if (m.matches())
       System.out.println(m.group(1));
      else
       System.out.println("no match");
    }run: java NthMatch "aa bb cc dd" 2
    does that help?
    what kind of framework you have to squeese the regex in?
    what do you want to do with that regex?
    do you want to check if Nth word maches something, or do you want to retriev that Nth string? or are you trying to do anything else?
    your explanation is unfortunatelly not sufficient :(

  • 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

  • Finding the second space in a string

    I am working on a query and having issues with getting the results I am looking for.  Below is an example of the string and the output that I need.
    String:
    Summer 2003 Quarter
    Autumn 2003 Quarter
    Winter 2004 Quarter
    Desired Output:
    Summer 2003
    Autumn 2003
    Winter 2004
    Any advice would be appreciated.

    Based on the posted data
    SELECT parsename(replace(col1,' ','.'),3)+ ' '+ parsename(replace(col1,' ','.'),2)
    FROM
    (SELECT 'Summer 2003 Quarter' col1
    UNION 
    SELECT'Autumn 2003 Quarter'
    UNION
    SELECT 'Winter 2004 Quarter'
    ) AS t
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • How to find the first occurrence of a string2 in string1

    Hello
    I've got a string, and I want to know where '-' occurs
    the first time. I mean, in 'hello-world', the first
    one is position 5.
    In C++, I've got:
    Result      = strcspn(string1, string2);
    How can I do it in Java?
    Thank you very much.

    String.indexOf()...read the API.

  • Finding the total size of a string when number of characters are known.

    Hi: I am having trouble inserting a field in a record that is CLOB. The number of characters in the string is 59298. Any idea how to know what is the size of this string? I am trying to figure out if I am exceeding the size of the string. The error I get is the following
    ORA-06512: at "SYS.DBMS_LOB", line 789
    ORA-06512: at line 1
    Second exception: ORA-21560: argument 2 is null, invalid, or out of range
    ORA-06512: at "SYS.DBMS_LOB", line 789
    Thanks
    Ray

    Either your stacktrace is incomplete or you make something wrong by copy/paste. And please, by providing sql/plsql code, use the tags [ code ] [ / code ] or [ pre ] [ / pre ], otherwise it is very hard to read.
    Here is small demonstration of what i mean by 3rd parameter:
    SQL> CREATE TABLE T_LOB(ID NUMBER,MESSAGE CLOB)
      2  /
    Table created.
    SQL> DECLARE
      2  l_clob CLOB;
      3  BEGIN
      4  INSERT INTO t_lob VALUES(1,'Hello')
      5  RETURNING message INTO l_clob;
      6  dbms_lob.writeappend(l_clob,length(',world'));
      7  END;
      8  /
    dbms_lob.writeappend(l_clob,length(',world'));
    ERROR at line 6:
    ORA-06550: line 6, column 1:
    PLS-00306: wrong number or types of arguments in call to 'WRITEAPPEND'
    ORA-06550: line 6, column 1:
    PL/SQL: Statement ignored
    SQL> DECLARE
      2  l_clob CLOB;
      3  BEGIN
      4  INSERT INTO t_lob VALUES(1,'Hello')
      5  RETURNING message INTO l_clob;
      6  dbms_lob.writeappend(l_clob,length(',world'),',world');
      7  END;
      8  /
    PL/SQL procedure successfully completed.
    SQL> SELECT * FROM t_lob
      2  /
            ID MESSAGE
             1 Hello,worldIn your examples, after length('some lengthy string...' there is no more parameters to dbms_lob.writeappend ( or i don't see any).
    Best regards
    Maxim

  • Find the width of a text string inside a text box?

    Hi,
    I have a text box with a long text string in it. I would like to know what the width of the text string is so that I can scroll it inside the textbox using the text box scrollviewer.
    var sv = this.foodieItemText.GetFirstDescendantOfType<ScrollViewer>();
    sv.ScrollToHorizontalOffsetWithAnimation(this.foodieItemText.Width, 20);
    The scrolling works fine but I don't know what value to use for the width offset in the first argument to ScrollToHorizontalOffsetWithAnimation. For my purposes I want it to scroll the full length of the text string (which is longer than the actual with of
    the text box). Any ideas?

    Hi duffybr,
    Yes, there is a ScrollViewer inside TextBox template and we could scroll to the specific position as we need, however there is no direct way to get the string width in TextBox, however we could get the width in TextBlock, by measure method.
    See this discussion for more information:
    http://stackoverflow.com/questions/9126076/how-can-i-calculate-the-width-of-a-string-in-metro-without-displaying-it
    Besides, there are some third party libraries help us get the String width.
    --James
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Finding the smallest letter in a single alphanumeric string

    How do I find the smallest letter in a single alphanumeric input?
    I already wrote and successfully tested the code that takes an alphanumeric string as input, separates the number from the alphabet, and creates a new alphabetic string. However, I'm unsuccesful in writting the code to find the smallest letter within the alphabetic string. I am almost certain that the easy answer is Arrays.sort, but I unsuccesfully tried writing the code to place the alphabetic string into an array. I researched compareTo, but I do not have another object to compare?! Any suggetsions?

    Ahh flaimbait - I'm sure I'll get criticized for this... but - while we are talking about time-to-market, etc...:
    The most important issue in development is to make sure that you understand the project requirements. The requirements in this situation were:
    Find the smallest character in a string.
    Given that, then any developer that goes through the trouble of looking up the sort APIs, etc... is not helping themselves - all they really needed to do was to write one line of code (as xxxx graciously posted):
    for (int x=0; x<foo.length(); x++) if (foo.charAt(i)<low) low=foo.charAt(x);I absolutely guarantee that any Java programmer could write the above faster than they could figure out how to split a string appart by characters, look up the arraysort API, etc...
    The arraysort functions are EXTREMELY efficient, and I would never suggest that someone re-implement them. The point here is that just because you've got a wrecking ball available, you can still use a hammer to drive a nail.

  • Find the length of a string in pixels

    Hello all,
    Wondering if there's a way in PowerShell to find the length of a given string in pixels?

    That would depend on the font used to draw it, including size, bold / italic, etc.  Assuming you know those things, there's a TextRenderer.MeasureText method in the Windows Forms library:
    $string = 'This is my string. There are many like it, but this one is mine.'
    $font = New-Object System.Drawing.Font('Arial', 12, [System.Drawing.FontStyle]'Bold, Italic')
    $size = [System.Windows.Forms.TextRenderer]::MeasureText($string, $font)
    $size.Width

  • How find shape containing all pixels in string drawn at angle?

    I've drawn a string on a JPanel at an angle using the code below. I want the mouse to turn into a hand when hovering over it but I don't know how to find the shape that an angled string comprises. (I can do it if it's written horizontally). How would I calculate that?
    double theta = Math.toRadians( angle );
    AffineTransform transform = AffineTransform.getRotateInstance( theta );
    ( ( Graphics2D ) graphics ).setTransform( transform );
    graphics.drawString( text, x, y );

    For the String you can create a Rectangle where the String is contained when it has no rotation. After that you can create Area (see java.awt.geom.Area) from the Rectangle and use transform() method of area to get a rotated one. Then just use contains() method.
    Regards,
    Stas

  • Function to replace nth occurrence of a character

    Hi,
    Is there a function already to replace the nth occurrence of a character ?
    For example: 'ORACLE IS THE INFORMATION COMPANY'
    Replace 3rd 'O' from left with 0 (Zero):
    'ORACLE IS THE INFORMATI0N COMPANY'
    Thanks !
    Regrads,
    Pat

    SQL> var a varchar2(100);
    SQL> var occ number;
    SQL> exec :a := 'ORACLE IS THE INFORMATION COMPANY';
    PL/SQL procedure successfully completed.
    SQL> exec :occ := 3;
    PL/SQL procedure successfully completed.
    SQL> select SUBSTR(:A,1, instr(:A,'O',1,:occ)-1)||'0'||SUBSTR(:A,instr(:A,'O',1,:occ)+1) from dual
      2  /
    SUBSTR(:A,1,INSTR(:A,'O',1,:OCC)-1)||'0'||SUBSTR(:A,INSTR(:A,'O',1,:OCC)+1)
    ORACLE IS THE INFORMATI0N COMPANYKarthick.

  • OBIEE - Find position of the last occurrence of a charcter within a string.

    Hi,
    I have a requirement in 11.1.1.6.9 to be locate the position of the last occurrence of a character within a string.
    i.e. Given the following, I would want to locate the last "/":
    This/is/an/exampleI would like to return a value of 11. Now, there could be any number of "/" so I can't always locate the nth one - it must be the last one.
    Anyone any ideas?
    Thanks,
    John

    Your requirement is not complete. just in case you want to extract the last part 'example' just use substring and replace to trim up to required part.
    You may have to go for the same for multiple times.
    ETL is the best to handle this than BI.
    BTW: Check this How to use locate function if multiple occurences of same character
    Edited by: Srini VEERAVALLI on May 10, 2013 10:25 AM
    Good that given link is helped you to solve it ;)
    Edited by: Srini VEERAVALLI on May 13, 2013 7:47 AM

Maybe you are looking for