Replace Number of Occurences in String

Hi All,
I just wanted to know what is the best way to replace a string within another string for certain number of times.
I dont want to replace only the first one.
I dont want to replace all of them either.
i'm looking for something like this:
replace(input_str, old_str, new_str, nb_occurences)
e.g: replace("1xxxx0xxxx4","xx",HH,3) should print 1HHHH0HHxx4
Thanks a lot in advance.

Better to use regex. I'd throw this away.Actually, he is using regex, but that just makes it worse. I'd throw it away, too.
What's wrong with java.lang.String's replaceAll method?He's doing a specific number of replacements, i.e., more than one, but not all.
There's so much wrong with that code, all I can say is to re-read the last line of my previous reply and DON'T USE RECURSION! Also, please abide by the Java naming conventions: method and variable names should start with lowercase letters and should always use camelCase, not under_scores. In the meantime, here's a somewhat radical solution: public class Test
  public static void main(String... args)
    String str = "One and two and three and four and five";
    System.out.println(replaceSome(str, "and", "OR", 0));
    System.out.println(replaceSome(str, "and", "OR", 2));
    System.out.println(replaceSome(str, "and", "OR", 3));
    System.out.println(replaceSome(str, "and", "OR", -1));
  static String replaceSome(String orig, String oldStr, String newStr, int reps)
    String[] parts = orig.split("\\Q" + oldStr + "\\E", reps + 1);
    int n = parts.length - 1;
    if (n > 0)
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < n; i++)
        sb.append(parts).append(newStr);
sb.append(parts[n]);
return sb.toString();
else
return parts[0];

Similar Messages

  • 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

  • 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++;

  • I need to WAP to count the number of occurences of an alphabet in a string.

    I need to WAP to count the number of occurences of an alphabet in a string.I tried a lot and have surfed a lot regarding this problem.
    I m not the most proficient with java.but this is all i could come up with,and would appreciate some help here.I hope you guys would help me find a solution to this.
    e.g String : abcabrty
    Result should be
    a:2
    b:2
    c:1
    r:1
    t:1
    y:1
    public class chkoccurences
         public static void main(String args[ ])
              String user_Data=args[0];
              int counter=0;     
              try
                   for(int i=0;i<user_Data.length( );i++)
                        for(int j=0;j<user_Data.length( );j++)
                             if(user_Data.charAt(i) == user_Data.charAt(j))
                             counter++;
                        System.out.println(user_Data.charAt(i)+" exists "+counter+" time(s) in the word.");
                   System.out.println(" ");
              catch(ArrayIndexOutOfBoundsException e)
                   System.out.println("Check the array size.");
    }This is the output i get out of the program:
    a exists 2 time(s) in the word.
    b exists 4 time(s) in the word.
    c exists 5 time(s) in the word.
    a exists 7 time(s) in the word.
    b exists 9 time(s) in the word.
    r exists 10 time(s) in the word.
    t exists 11 time(s) in the word.
    y exists 12 time(s) in the word.What i think is i need an array to store the repeated characters because the repeated characters are getting counted again in the loop,if you know what i mean.
    Please, i would appreciate some help here.

    Criticism is welcomed
    public class tests {
         final int min = 10;
         final int max = 35;
         final char[] chars = new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
                   'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
                   'v', 'w', 'x', 'y', 'z'};
         public static void main(String[] args){
              tests t = new tests();
              String[] strings = new String[] {"aabcze", "att3%a", ""};
              for(String s : strings){
                   System.out.println(t.getAlphaCount(s));
         public String getAlphaCount(String s){
              int[] alphaCount = new int[26];
              int val;
              for(char c : s.toCharArray()){
                   val = Character.getNumericValue(c);
                   if( (val>=min) && (val<=max)){
                        alphaCount[val-min]++;
              StringBuilder result = new StringBuilder();
              for(int i=0; i<alphaCount.length; i++){
                   if(alphaCount[i] > 0){
                        result.append(chars[i] + ":" + alphaCount[i] + ", ");
              if(result.length() != 0){
                   result.delete(result.length()-2, result.length());
              return result.toString();
    }

  • How to find out the number of occurence of special character

    Hi ,
    I have a string coming coming in I/p which is like '1;2;100;201;'
    I need to break up this string and run my process for each value ( i.e for 1,2,100 and 201).
    How i can know the count of number of occurences of ';' character?
    How i can loop so that it runs once for each value?

    1. Split, pre Oracle 10g...
    ===========================
    with t as (select '10,aaaa,20,vvvvv,30,xxx''xx,12,12,56' txt from dual)
    select substr( txt
                 , decode(level, 1, 1, instr(txt, ',', 1, level-1)+1)
                 , decode(instr(txt, ',', 1, level), 0, length(txt), instr(txt, ',', 1, level)
                   - decode(level, 1, 0, instr(txt, ',', 1, level-1))-1)
                 ) val
    from t
    connect by level <= length(txt)-length(replace(txt,','))+1
    VAL
    10
    aaaa
    20
    vvvvv
    30
    xxx'xx
    12
    12
    56
    9 rows selected.2. Split, 10g onwards using regular expressions
    ===============================================
    with t as (select 'aaaa,,bbbb,cccc,dddd,eeee,ffff' as txt from dual)
    -- end of sample data
    select REGEXP_SUBSTR (txt, '[^,]+', 1, level)
    from t
    connect by level <= length(regexp_replace(txt,'[^,]*'))+1
    REGEXP_SUBSTR(TXT,'[^,]+',1,LE
    aaaa
    bbbb
    cccc
    dddd
    eeee
    ffff
    7 rows selected.example usage with varying IN clause...
    SQL> ed
    Wrote file afiedt.buf
      1  select *
      2  from emp
      3  where ename in (
      4    with t as (select '&input_string' as txt from dual)
      5    select REGEXP_SUBSTR (txt, '[^,]+', 1, level)
      6    from t
      7    connect by level <= length(regexp_replace(txt,'[^,]*'))+1
      8*   )
    SQL> /
    Enter value for input_string: SCOTT,JAMES
    old   4:   with t as (select '&input_string' as txt from dual)
    new   4:   with t as (select 'SCOTT,JAMES' as txt from dual)
         EMPNO ENAME      JOB              MGR HIREDATE                   SAL       COMM     DEPTNO
          7788 SCOTT      ANALYST         7566 19-04-1987 00:00:00       3000                    20
          7900 JAMES      CLERK           7698 03-12-1981 00:00:00        950                    30
    SQL>3. Split 10g onwards using XMLTABLE...
    ======================================
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (select 'This is some sample text that needs splitting into words' as txt from dual)
      2  select x.*
      3  from t
      4      ,xmltable('x/y'
      5                passing xmltype('<x><y>'||replace(t.txt,' ','</y><y>')||'</y></x>')
      6                columns word varchar2(20) path '.'
      7*              ) x
    SQL> /
    WORD
    This
    is
    some
    sample
    text
    that
    needs
    splitting
    into
    words
    10 rows selected.

  • Reliable detect number of occurences (table lock needed or ?)

    Hi all,
    I got an issue with detecting duplicate messages. Database clients process files and messages and create a hash value that is passed on to the database. The database should return the number of occurences of this hash value in the last (e.g) 14 days.
    create table HashHistory ( ID NUMBER,
    MESSAGEHASH VARCHAR2 (20),
    TS TIMESTAMP);
    create sequence SomeSequence;
    insert into HashHistory values (SomeSequence.nextval,'first hash', systimestamp);
    insert into HashHistory values (SomeSequence.nextval,'second hash', systimestamp);
    create or replace procedure DuplDetection  (p_HashIn varchar2,
                                         p_occurences OUT number) AS
    l_timestamp timestamp default systimestamp;                          
    begin
      -- possible exclusive table lock here... lock table HashHistory in exclusive mode;
      insert into HashHistory values (SomeSequence.nextval, p_HashIn, l_timestamp);
      select count (1)
      into p_occurences
      FROM HashHistory
      where MESSAGEHASH = p_HashIn
      and   TS < l_timestamp
      and   TS > l_timestamp-14;
      commit; --to release the table lock if applicable
    end;When this procedure is called by two different machines at the same time with the same new hash value ('third hash'). One session should return 0 while the other should return 1 as number of occurences.... With default Oracle behaviour using row level locks, and executing them in parallel both sessions will not be able to see the others sessions hash values, and both will return 0 occurences. Is an exclusive table lock my only option to enforce this behaviour or can I trust Oracle to handle this correctly?
    I expect 10^6 hashes each day and possible up to 10 or 20 clients running at the same time generating and checking these hash values. What are the changes of both sessions returning the same value without an exclusive table lock (as in this example)? What other parameters would you consider?
    I am on Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi

    Nicosa wrote:
    Hi,
    Wouldn'that work if you do it as follows ?insert into HashHistory values (SomeSequence.nextval, p_hashIn,...);
    commit;
    select count (1)
    into p_occurences
    FROM HashHistory
    where MESSAGEHASH = p_HashIn
    and   TS > l_timestamp-14
    and ID!=SomeSequence.currval;The second session should see that some others existing hash were inserted, and hence an be warned.No, it wouldn't work. Some kind of synchronization is required.
    In multi-threaded environment you cannot predict the order of execution of this program.
    Let say we have a server with only one processor and 3 users (sessions) connected to that server.
    Three users (let say U1, U2 and U3) call this procedure to insert the same hash. The procedure has 3 operations: insert, commit, select,
    and assume theoretically that these 3 operation are atomic (each takes only one processor cycle - in reality each of these operations can consume thousands of cycles).
    Server can execute these calls in this order:
    U1-insert (sequence + 1)
    U1-commit
    U1-select (returns 0)
    U2-insert (sequence + 1)
    U2-commit
    U2-select (returns 1)
    U3-insert (sequence + 1)
    U3-commit
    U3-select (returns 2)
    - in this scenario results will be OK.
    But the order might be:
    U1-insert (sequence + 1)
    U1-commit
    - here server decides to switch to another process/thread
    U2-insert (sequence + 1)
    U2-commit
    - server switches to proccess 3
    U3-insert (sequence + 1)
    U3-commit
    - server switches back to U2
    U2-Select (user 2 sees record commited by U1 and U3 and returns 2)
    - server switches to U3
    U3-Select (user 1 sees record commited by U1 and U2 and returns 2)
    - server switches to U1
    U1 - Select (this also returns 2)
    - results are 2,2,2, but should be 0,1,2
    If 20 users cal this procedure at the same moment with the same hash value, it is even possible that each user gets 19 as the final result,
    but proper results should be 0, 1, 2, 3 .... 19 ;)
    Without some kind of synchronization this a lottery.
    There is also another trap with the sequence - consider this example:
    Session 1
    SQL> create sequence abc;
    Sequence created.
    SQL> select abc.nextval from dual connect by level <=5;
       NEXTVAL
          1
          2
          3
          4
          5
    SQL> select abc.currval from dual;
       CURRVAL
          5Session 2
    SQL> select abc.nextval from dual;
       NEXTVAL
          6
    SQL> select abc.nextval from dual connect by level <=5;
       NEXTVAL
          7
          8
          9
         10
         11
    SQL> select abc.currval from dual;
       CURRVAL
         11Back to session 1
    SQL> select abc.currval from dual;
       CURRVAL
          5What happens in this scenario:
    - user 1 does insert (select nextval from the sequence)
    - user 2,3,4,5,6 ..... 100 call the procedure just 3 microseconds after U1 and do insert (increase the sequence)
    - user 1 retrieve currval from the sequence ?

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

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

  • Error 5 occurred at Open/Create/Replace File in Write spreadsheet String.vi

    Hi everyone,
    can anyone help me with this problem?
    "error 5 occurred at Open/Create/Replace File in Write spreadsheet String.vi "
    I've been using this part of the program for over a year an suddenly this error occures. But not always, mainly at the very beginning of my tests when the file should not be open.
    Info: I'm using a realtime PXI-System. Maybe the amount of data can cause the problem? (about 2MB)
    Grüße
    Meike
    Attachments:
    writeResults.jpg ‏345 KB
    error5.jpg ‏52 KB

    Hi Meike,
    is the file opened by a different program? Do you try to access it by FTP in parallel to your VI?
    You could use basic file functions instead of WriteSpreadsheetFile. That way you could open the file before starting the loop, keep it open all the time and close it once you're finished - with the added benefit of easier error handling…
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Replacing a character in a string to another character

    hi,
    i need to write a function or procedure to replace the character of a string value suppose:
    l_error:= 'abcdefghijklmnop' is a string
    i need write a function or procedure to replace the character "c" to "z"
    that data in l_error is not in any table.
    thanks,
    AJ

    I want to Replace all the Existence of the word - "Test" in a string with "Test1" whereever a space exits before the word Test and someother alphabet after "Test" i.e. Test will be replaced with Test1 if a word starts with Test and contains more alphabets also. For example - TestName should be replaced with Test1Name while MyTest should not be updated to MyTest1.
    I have tried to use below query which uses oracle regular expressions -
    SELECT REGEXP_REPLACE('MYCOMPANY TEST TESTGEET INDIA PVT LTD TEST','\s(TEST)\w',' TEST1') FROM DUAL
    Output -
    "MYCOMPANY TEST *TEST1EET* INDIA PVT LTD TEST"
    Here, it has also replaced the G also from TESTGEET and resulted in TEST1EET while i want TEST1GEET.
    Can someone please suggest how can i do this..... may b m doing some silly mistake but sorry m a newbie to regular expression...
    Thanks in advance..

  • Server 2012 errors for timeout -- LDAP error number: 55 -- LDAP error string: Timeout Failed to get server error string from LDAP connection

    Hello, currently getting below error msg's utilizing software thru which LDAP is queried for discovering AD objects/path and resource enumeration and tracking.
    Have ensured firewalls and port (389 ) relational to LDAP are not closed, thus causing hanging.
    I see there was a write up on Svr 2003 ( https://support.microsoft.com/en-us/kb/315071 ) not sure if this is applicable, of if the "Ntdsutil.exe" arcitecture has changed much from Svr 03. Please advise. 
    -----------error msg  ----------------
    -- LDAP error number: 55
    -- LDAP error string: Timeout Failed to get server error string from LDAP connection

    The link you shared is still applicable. You can adjust your LDAP policy depending on your software requirements.
    I would also recommend that you in touch with your software vendor to get more details about the software requirements.
    This posting is provided AS IS with no warranties or guarantees , and confers no rights.
    Ahmed MALEK
    My Website Link
    My Linkedin Profile
    My MVP Profile

  • How to replace a character in a string with blank space.

    Hi,
    How to replace a character in a string with blank space.
    Note:
    I have to change string  CL_DS_1===========CM01 to CL_DS_1               CM01.
    i.e) I have to replace '=' with ' '.
    I have already tried with <b>REPLACE ALL OCCURRENCES OF '=' IN temp_fill_string WITH ' '</b>
    Its not working.

    Hi,
    Try with this..
    call method textedit- >replace_all
      exporting
        case_sensitive_mode = case_sensitive_mode
        replace_string = replace_string
        search_string = search_string
        whole_word_mode = whole_word_mode
      changing
        counter = counter
      exceptions
        error_cntl_call_method = 1
        invalid_parameter = 2.
    <b>Parameters</b>      <b> Description</b>    <b> Possible values</b>
    case_sensitive_mode    Upper-/lowercase       false Do not observe (default value)
                                                                       true  Observe
    replace_string                Text to replace the 
                                         occurrences of
                                         SEARCH_STRING
    search_string                 Text to be replaced
    whole_word_mode          Only replace whole words   false Find whole words and                                                                               
    parts of words (default                                                                               
    value)
                                                                               true  Only find whole words
    counter                         Return value specifying how
                                        many times the search string
                                        was replaced
    Regards,
      Jayaram...

  • Replacing the \ character in a string

    I'm having trouble replacing a backslash in a string. I use .indexOf() to find the character, but I have to use an escape character and write .index("\\"), but it doesn't work - it returns -1.
    Also, replace() doesn't work - gives me an java.util.regex.PatternSyntaxException. Any ideas?
    thx

    The escape is for the compiler, I think, and then you need to escape the backslash.
    Try "\\\\".
    � {�                                                                                                                                                                                                           

  • What api would I use to get the number of chars in string?

    What api would I use to get the number of chars in string?

    Assuming that you really mean that you want the number of charaters in a String (not string), that would be documented in java.lang.String
    The method is length()

  • Get the number of occurences in a text

    Hi,
    Is there any way by which i can check the number of occurences of a word in a text ???
    for eg. i an have 'i am a good boy and i am a good man'
    i wnt to check the number of occurences of good in the above statemnt
    Ny way to do that..........
    Thanks

    Well, it was a silly suggestion from me regarding ";" or "." - of course they are nonword characters.
    Basically, the issue is the same as with
    SQL> with t as (
      2    select ' good good good good good good ' s from dual
      3  )
      4  select
      5  s,
      6  regexp_count(s,' good ') reg_count
      7  from t
      8  ;
    S                                REG_COUNT
    good good good good good good           3And i don't see at the moment a simple workaround...
    Best regards
    Maxim

Maybe you are looking for

  • Submenu's not showing up in IE7

    I just finished a site with pull-down menus that I modified somewhat from Spry. The sub-menu which is under the link "Services" works great in Safari and FF but does not work at all in IE7. A few people have pointed out some CSS conflicts that showed

  • How to get into /Expanded/ List View

    I have a bunch of metadata that I have turned on for Expanded List View and I am in Browser View with the little "List" icon checked (I guess this is next to "grid view") but I can't seem to find a pulldown or tab or checkbox that lets me know I am i

  • Planning IOndicator in control tab page-Work order

    How does the system assign the indicator "Unplanned, planned and Immediate" to a work order. What are the fields it considers when assigning the Planning indicator in Control tab page of the work order

  • DB links dependencies

    HI, How can I retrieve what are all the objects (packages, views, synonyms etc) are calling the DBLINK name. Thanks in advance.

  • IW31 - own status profile for operations

    Hi, we need some additional user status for operations in IW31, IW32, IW33 for service orders. Therefore we created a new status profile in customizing (tx OIBS). But it is unclear which objecttype(s) we have to assign to this status profile. Could o