Replacing a single occurance in a string

if i do string.replaceAll(old,new) then it replaces every occurance in the string
how can i only replace the first found occurance in the string or even better specify where in the string i want to start looking
so if i have
hello hello hello hello
i can say
string.replace(5,"hello", "yellow")
and it will give me
hello yellow hello hello

ive come up with this
SNIP
it seems to be doing the trick (so far)Good one! I guess the same is actually done with StringBuffer.replace()
jTPdisplay.setText(new StringBuffer(f).replace(pos, pos+f.length(), r).toString());It should be something like this. :)

Similar Messages

  • How do I replace a single instance of a string?

    I'm trying to replace a certain string in a text file. The problem is, there is other data in the text file that is being affected by the replace() function, since replace() replaces each substring that fits the pattern it's looking for. I want my replacement function to target one single instance of something, at one specific instance, and to leave the rest of my text alone.
    Any thoughts on how I'd do that?

    I don't see how to do it with a String direclty without making silly copies.
    But it seems you could use a StringBuilder and its method replace(int start, int end, String str).
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html#replace(int,%20int,%20java.lang.String)

  • Reg: Replacement of second occurance of character in string

    Hi,
    Consider one string1 =  'ABCDAE' OR  string2 = 'SHEETAL'.
    I want to replace the second occurance of A in above string1.and second occurance of E in above string2 with any differnt character.
    I tried with offset calculation , length , replace , split stmts.
    but always first occurance is getting replace.
    Please provide your ideas.
    Regards,
    Shital

    Hi,
    Try this.
    data: string1 type char10 value 'ABCDAE',
            len     type i.
      write: / string1.
      search string1 for 'A'.
      if sy-subrc = 0.
        add 1 to sy-fdpos.
        len = strlen( string1 ) - sy-fdpos.
        replace 'A' in string1+sy-fdpos(len) with '!'.
        write: / string1.
      endif.
    Darren

  • Identify and replace a single quote in an In Parameter

    Can anyone tell me the syntax for finding and replacing a single quote in a user entered string? Thanks.

    Cav,
    I tried this:
    insert into emp values (9999,''''||'Must', 'ddd',7902, sysdate, 2000, null, 10) ;
    select * from emp;
         EMPNO ENAME      JOB              MGR HIREDATE          SAL       COMM     DEPTNO
          7369 SMITH      CLERK           7902 17-12-1980        800                    20
          7499 ALLEN      SALESMAN        7698 20-02-1981       1600        300         30
          7521 WARD       SALESMAN        7698 22-02-1981       1250        500         30
          7566 JONES      MANAGER         7839 02-04-1981       2975                    20
          7654 MARTIN     SALESMAN        7698 28-09-1981       1250       1400         30
          7698 BLAKE      MANAGER         7839 01-05-1981       2850                    30
          7782 CLARK      MANAGER         7839 09-06-1981       2450                    10
          7788 SCOTT      ANALYST         7566 19-04-1987       3000                    20
          7839 KING       PRESIDENT            17-11-1981       5000                    10
          7844 TURNER     SALESMAN        7698 08-09-1981       1500          0         30
          7876 ADAMS      CLERK           7788 23-05-1987       1100                    20
          7900 JAMES      CLERK           7698 03-12-1981        950                    30
          7902 FORD       ANALYST         7566 03-12-1981       3000                    20
          7934 MILLER     CLERK           7782 23-01-1982       1300                    10
          9999 'Must      ddd             7902 29-08-2005       2000                    10
    select * from emp where ename = ''''||'Must';
         EMPNO ENAME      JOB              MGR HIREDATE          SAL       COMM     DEPTNO
          9999 'Must      ddd             7902 29-08-2005       2000                    10Hope this helps
    Ghulam

  • How do I find & replace a single character?

    Am using Adobe Acrobat Pro....
    The find/replace box pull down has "Whole Words Only" checked and I cannot uncheck it.  How can I find and replace a single character throughout a document?

    That's just how it works. You can "find" anything, but you can only "replace" whole words. As soon as you click to open the "replace" section of the dialog the search settings are locked into their basic states, even if you don't enter a replacement string (but that part's a bug).
    The simple answer is that you cannot replace all instances of one character using Acrobat's inbuilt tools. You're expected to edit the document outside of PDF and recreate it.

  • Manipulating single characters inside a string?

    Hello CF Experts,
    I feel a little stupid having to ask this, but I might be suffering from mental block:
    I need to manipulate single characters inside a string. Lets say I have a string "-----" (5 hyphens) and
    I want to replace the hyphen at position #pos# with "X".
    I tried using the Mid() function, but that apparently is read-only:
         <cfset Mid(string,#pos#,1) = "X">   
    results in an error.
    Of course I can do string concatenation like
         <cfset string = Mid(string,1,#pos#-1) & "X" & Mid(string,#pos#+1,Len(string)-#pos#)
    or use the Insert/RemoveChars functions:
         <cfset string = Insert("X",string,#pos#-1)>
         <cfset string = RemoveChars(string,#pos#+1,1)>
    but this seems awfully awkward.
    There must be a more elegant solution. Any hints?
    Regards, Richard

    Strings are immutable, so one can't "edit" one, all one can do is create a new one based on an existing one.  So your insert() / removechars() approach is fine.  Or one could use left() & mid() (or right()), or replace() or... all variations on a fairly similar theme.
    (http://en.wikipedia.org/wiki/Immutable_object#Java)
    Adam

  • Finding location of single quote ( ' ) in a string

    Hi,
    I have a need to find the location of second single quote in a string.
    Below query works fine for a string without single quote. It gives me the location of word 'HIER' for 2nd occurrence.
    select instr('HIER A HIER B','HIER',2) from dual
    I want to do the same with single quote. I am trying with the below query.
    select instr('HIER A '' HIER B ''',chr(39),2) from dual
    But it always gives me the location of first occurrence of single quote and not the second.
    Any idea about this issue..?
    Thanks

    select regexp_replace('AND ( ACCT_V.HIER_NODE_NM = ''D0100'' AND TODAYS_DATE IS NULL ','.*''(.*)''.*','\1') from dual
    select substr('AND ( ACCT_V.HIER_NODE_NM = ''D0100'' AND TODAYS_DATE IS NULL ',instr('AND ( ACCT_V.HIER_NODE_NM = ''D0100'' AND TODAYS_DATE IS NULL ','''')+1,instr('AND ( ACCT_V.HIER_NODE_NM = ''D0100'' AND TODAYS_DATE IS NULL ','''',1,2)-instr('AND ( ACCT_V.HIER_NODE_NM = ''D0100'' AND TODAYS_DATE IS NULL ','''')-1) from dualComment to the second approach: check SUBSTR() syntax, the second numeric parameter is length of the fragment, not the ending position. Still, RE approach is way shorter and more readable, isn't it? ;)

  • [JS - CS3]  Can't REPLACE A with B within a string? Help Please...

    Hello Experts,
    First off - I'm a newbee to all this JS and especially with CS3.
    I have a string: '
    b myDocumentName
    which can have it's value as: '
    b 00000en_ Generator WX/WY
    Problem is, backshlashes ( / )are a bad thing for me...
    b Question:
    How can I do a 'replace' operation to replace the '/' from the string with a '_'?
    I have at the moment:
    > var myDocSaveName = oneResult[3]+oneResult[4]+oneResult[5];
    > myDocSaveName.replace(what "/", with "");
    > myDoc.save ("C:/DATA/"+myDocSaveName, undefined, undefined, true)
    I get an error Nr. 25... Offending text:"/"
    What am I doing wrong?

    'what' and 'with' are the names of those arguments. They should not be included in the statement:
    myDocSaveName.replace("/", "");
    But that still won't work because replace doesn't operate on a string in situ, it returns the modified string. So:
    myDocSaveName = myDocSaveName.replace("/", "");
    This too has its limitations. It'll change only the first instance of "/", not all of them. To change all of them, you need to restate the 'what' as a RegExp:
    myDocSaveName = myDocSaveName.replace(/\//g, "_");
    A RegExp literal is delimited by the "/" character, so to have it, alone, as the character to be sought you must use the backslash to escape the character. Then, to indicate you want the replace to happen globally within the string, you add the 'g' after the RegExp.
    Dave

  • Replacing a special character in a string with another string

    Hi
    I need to replace a special character in a string with another string.
    Say there is a string -  "abc's def's are alphabets"
    and i need to replace all the ' (apostrophe) with &apos& ..which should look like as below
    "abc&apos&s def&apos&s are alphabets" .
    Kindly let me know how this requirement can be met.
    Regards
    Sukumari

    REPLACE
    Syntax Forms
    Pattern-based replacement
    1. REPLACE [{FIRST OCCURRENCE}|{ALL OCCURRENCES} OF]
    pattern
              IN [section_of] dobj WITH new
              [IN {BYTE|CHARACTER} MODE]
              [{RESPECTING|IGNORING} CASE]
              [REPLACEMENT COUNT rcnt]
              { {[REPLACEMENT OFFSET roff]
                 [REPLACEMENT LENGTH rlen]}
              | [RESULTS result_tab|result_wa] }.
    Position-based replacement
    2. REPLACE SECTION [OFFSET off] [LENGTH len] OF dobj WITH new
                      [IN {BYTE|CHARACTER} MODE].
    Effect
    This statement replaces characters or bytes of the variable dobj by characters or bytes of the data object new. Here, position-based and pattern-based replacement are possible.
    When the replacement is executed, an interim result without a length limit is implicitly generated and the interim result is transferred to the data object dobj. If the length of the interim result is longer than the length of dobj, the data is cut off on the right in the case of data objects of fixed length. If the length of the interim result is shorter than the length of dobj, data objects of fixed length are filled to the right with blanks or hexadecimal zeroes. Data objects of variable length are adjusted. If data is cut off to the right when the interim result is assigned, sy-subrc is set to 2.
    In the case of character string processing, the closing spaces are taken into account for data objects dobj of fixed length; they are not taken into account in the case of new.
    System fields
    sy-subrc Meaning
    0 The specified section or subsequence was replaced by the content of new and the result is available in full in dobj.
    2 The specified section or subsequence was replaced in dobj by the contents of new and the result of the replacement was cut off to the right.
    4 The subsequence in sub_string was not found in dobj in the pattern-based search.
    8 The data objects sub_string and new contain double-byte characters that cannot be interpreted.
    Note
    These forms of the statement REPLACE replace the following obsolete form:
    REPLACE sub_string WITH
    Syntax
    REPLACE sub_string WITH new INTO dobj
            [IN {BYTE|CHARACTER} MODE]
            [LENGTH len].
    Extras:
    1. ... IN {BYTE|CHARACTER} MODE
    2. ... LENGTH len
    Effect
    This statement searches through a byte string or character string dobj for the subsequence specified in sub_string and replaces the first byte or character string in dobj that matches sub_string with the contents of the data object new.
    The memory areas of sub_string and new must not overlap, otherwise the result is undefined. If sub_string is an empty string, the point before the first character or byte of the search area is found and the content of new is inserted before the first character.
    During character string processing, the closing blank is considered for data objects dobj, sub_string and new of type c, d, n or t.
    System Fields
    sy-subrc Meaning
    0 The subsequence in sub_string was replaced in the target field dobj with the content of new.
    4 The subsequence in sub_string could not be replaced in the target field dobj with the contents of new.
    Note
    This variant of the statement REPLACE will be replaced, beginning with Release 6.10, with a new variant.
    Addition 1
    ... IN {BYTE|CHARACTER} MODE
    Effect
    The optional addition IN {BYTE|CHARACTER} MODE determines whether byte or character string processing will be executed. If the addition is not specified, character string processing is executed. Depending on the processing type, the data objects sub_string, new, and dobj must be byte or character type.
    Addition 2
    ... LENGTH len
    Effect
    If the addition LENGTH is not specified, all the data objects involved are evaluated in their entire length. If the addition LENGTH is specified, only the first len bytes or characters of sub_string are used for the search. For len, a data object of the type i is expected.
    If the length of the interim result is longer than the length of dobj, data objects of fixed length will be cut off to the right. If the length of the interim result is shorter than the length of dobj, data objects of fixed length are filled to the right with blanks or with hexadecimal 0. Data objects of variable length are adapted.
    Example
    After the replacements, text1 contains the complete content "I should know that you know", while text2 has the cut-off content "I should know that".
    DATA:   text1      TYPE string       VALUE 'I know you know',
            text2(18)  TYPE c LENGTH 18  VALUE 'I know you know',
            sub_string TYPE string       VALUE 'know',
            new        TYPE string       VALUE 'should know that'.
    REPLACE sub_string WITH new INTO text1.
    REPLACE sub_string WITH new INTO text2.

  • How can i replace backslashes with fowardslashes in a String

    Hi all,
    I hope someone can help me with this stupid problem iv been having, i need to replace all the backslashes in a String with forwardslashes.
    The method replace() doesnt work because it uses Chars, also i cant use replaceAll() because im restricted to using jdk1.3.
    I would really appreciate some help here,
    Thanks

    Or in other words, I have no idea what you're talking about:
    public class Foo {
         public static void main(String[] args) {
              String s = "string with \\ back \\ slashes \\ in \\ it !";
              System.out.println(s.replace('\\','/'));
    }

  • Finding Second occurance of a String

    Hi All,
    How can find the second occurance of a string in text.
    Is there any way to find that using contains string?
    Thanks in Advance
    Regards,
    Raghu

    Hi,
    <b>Check the sample coding done below using CS contains String operator</b>
    DATA: str TYPE string VALUE 'testing the test'.
    DATA: sub type string value 'test'.
    DATA: tempstr TYPE string.
    DATA: len TYPE i.
    DATA: rem_len type i.
    IF str CS sub.
      len = STRLEN( sub ) + sy-fdpos.
      rem_len = STRLEN( str ) - len.
      tempstr = str+len(rem_len).
    ENDIF.
    WRITE: tempstr.
    if tempstr CS sub.
    write: sy-fdpos. " This is the second occurances offset
    endif.
    Regards,
    Sesh

  • Single quote in the String????

    Hello All,
    I want to supress the meaning of single quote in the string, so that I can use the string as one of the fields in my sql query, for doing this inserting "/" before the single code is the way or is there any other standard way to achieve this.
    Thanks in Advance,
    Sarada.

    usually you need to use the scape character for stopping the meaning of a single qoute, or even double quite \', \"
    String s = "select empname from emps where id=\'123\'" ;
    Regards

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

  • Program to count the no. of times a character occurs in a string.

    program to count the no. of times a character occurs in a string.
    Say if u have a method :- Countclass(string s,char c) then using this u should be able to count a char ' T' in the string ="TESTING".
    So it is appering 2 times.
    How to count it.

    int countChar(String s, char c) {
       int count = 0;
       for (int i=0; i<s.length(); i++) {
          if (s.charAt(i) == c)
             count++;
       return count;
    }

  • What can be used for replacing SELECT SINGLE *   ?

    What can be used for replacing SELECT SINGLE *  for improving the performance in the following statements?
    SELECT SINGLE * FROM REGUV
       WHERE LAUFD = G_WLAUFD "RUN DATE ,SY-DATUM
         AND LAUFI = P_LAUFI.  "IDENTICATION NO
    SELECT SINGLE * FROM T100
       INTO CORRESPONDING FIELDS OF G_T100_WA
        WHERE SPRSL = G_T_IALLMESS-MSGSPRA
          AND ARBGB = G_T_IALLMESS-MSGID
          AND MSGNR = G_T_IALLMESS-MSGNR.
    SELECT SINGLE * FROM TBTCO
       INTO CORRESPONDING FIELDS OF TBTCO
        WHERE JOBNAME = FS_JOBNAME.

    If you need all the fields and you know that only one record exists then u need to use select single * only. You can improve the performance by specifying key fields in the where clause of select statements. If the structure of the work area or internal table in which you are fetching the data is same as that of the database table then no need to use corresponding fields clause.
    Best Regards,
    Vibha
    *Please mark all the helpful answers

Maybe you are looking for