Replace String in a String

How can I replace a String in a String ,for example :
in the String "Hello World" replace Hello with Bye" ?
Is there a class or code I can find for that purpose?

use an utility method like this :
I did not found an existing method doing this in java.lang.String or StringBufer
public static String replaceFirstSubstring(
String stringToSubstitute, String searchString, String replaceString) {
if (stringToSubstitute == null) {
return null;
int prefixEndIndex = stringToSubstitute.indexOf(searchString);
if (prefixEndIndex == -1) {
return stringToSubstitute;
int suffixStartIndex = prefixEndIndex + searchString.length();
StringBuffer newString = new StringBuffer(stringToSubstitute.substring(0, prefixEndIndex));
newString.append(replaceString).append(stringToSubstitute.substring(suffixStartIndex));
return newString.toString();
put it in a while if you need to replace more than 1 time

Similar Messages

  • Find and replace value in Delimited String

    Hi All,
    I have a requirement, where i need to find and replace values in delimited string.
    For example, the string is "GL~1001~157747~FEB-13~CREDIT~A~N~USD~NULL~". The 4th column gives month and year. I need to replace it with previous month name. For example: "GL~1001~157747~JAN-13~CREDIT~A~N~USD~NULL~". I need to do same for last 12 months.
    I thought of first devide the values and store it in variable and then after replacing it with required value, join it back.
    I just wanted to know if there is any better way to do it?

    for example (Assumption: the abbreviated month is the first occurance of 3 consecutive alphabetic charachters)
    with testdata as (
    select 'GL~1001~157747~FEB-13~CREDIT~A~N~USD~NULL~' str from dual
    select
    str
    ,regexp_substr(str, '[[:alpha:]]{3}') part
    ,to_date('01'||regexp_substr(str, '[[:alpha:]]{3}')||'2013', 'DDMONYYYY') part_date
    ,replace (str
             ,regexp_substr(str, '[[:alpha:]]{3}')
             ,to_char(add_months(to_date('01'||regexp_substr(str, '[[:alpha:]]{3}')||'2013', 'DDMONYYYY'),-1),'MON')
    ) res
    from testdata
    STR
    PART
    PART_DATE
    RES
    GL~1001~157747~FEB-13~CREDIT~A~N~USD~NULL~
    FEB
    02/01/2013
    GL~1001~157747~JAN-13~CREDIT~A~N~USD~NULL~
    with year included
    with testdata as (
    select 'GL~1001~157747~JAN-13~CREDIT~A~N~USD~NULL~' str from dual
    select
    str
    ,regexp_substr(str, '[[:alpha:]]{3}-\d{2}') part
    ,to_date(regexp_substr(str, '[[:alpha:]]{3}-\d{2}'), 'MON-YY') part_date
    ,replace (str
             ,regexp_substr(str, '[[:alpha:]]{3}-\d{2}')
             ,to_char(add_months(to_date(regexp_substr(str, '[[:alpha:]]{3}-\d{2}'), 'MON-YY'),-1),'MON-YY')
    ) res
    from testdata
    STR
    PART
    PART_DATE
    RES
    GL~1001~157747~JAN-13~CREDIT~A~N~USD~NULL~
    JAN-13
    01/01/2013
    GL~1001~157747~DEC-12~CREDIT~A~N~USD~NULL~
    Message was edited by: chris227 year included

  • Replace the text numbers string in a txt file using C++.. Help Me..

    Read a Document and replace the text numbers in a txt file using c++..
    For ex: 
    Before Document: 
    hai hello my daily salary is two thousand and five and your salary is five billion. my age is 
    twenty-five. 
    After Document: 
    hai hello my daily salary is # and your salary is #. my age is #. 
    All the text numbers and i put the # symbol.. 
    I am trying this code: 
    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;
    ifstream myfile_in ("input.txt");
    ofstream myfile_out ("output.txt");
    string line;
    void find_and_replace( string &source, string find, string replace ) {
    size_t j;
    for ( ; (j = source.find( find )) != string::npos ; ) {
    source.replace( j, find.length(), replace );
    myfile_out << source <<endl;
    cout << source << endl;
    int main () {
    if (myfile_in.is_open())
    int i = 0,j;
    //string strcomma ;
    // string strspace ;
    while (! myfile_in.eof() )
    getline (myfile_in,line);
    string strcomma= "two";
    string strspace = "#";
    find_and_replace( line , strcomma , strspace );
    i++;
    myfile_in.close();
    else cout << "Unable to open file(s) ";
    system("PAUSE");
    return 0;
    Please help me.. Give me the correct code..

    Open the file as a RandomAccessFile. Check its length. Declare a byte array as big as its length and do a single read to get the file into RAM.
    Is this a simple text file (bytes)? No problem. If it's really 16-bit chars, use java.nio to first wrap the byte array as a ByteBuffer and then view the ByteBuffer as a CharBuffer.
    Then you're ready for search/replace. Do it as you would in any other language. Be sure to use System.arraycopy() to shove your bytes right (replace bigger than search) or left (replace smaller than search).
    When done, a single write() to the RandomAccessFile will put it all back. As you search/replace, keep track of size. If the final file is smaller than the original, use a setLength() to the new size to avoid extraneous data at the end.

  • Replacing characters in a string

    I have an application where a user can enter information into a webform. I'm using JSP, but of course the backend there is a Java function also.
    I am trying to write a function which will replace when the user hits enter with a <br> (break tag).
    Right now it's a complicated, messy loop to look at each character and it has many flaws.
    Is there a "replace" function that will do this for me?
    However, I don't think in a webpage form it transfers the \n end of line characters.

    Nope compiler error
    symbol : method replaceAll (java.lang.String,java.lang.String)
    location: class java.lang.String
    return (txt.replaceAll("\n","<br>"));

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

  • Problem in replacing characters of a string ?

    Hello everybody,
    I want to replace a few characters with their corresponding unicode codepoint values.
    I have a userdefined method that gets the unicode codepoint value for a character.
    1. I want to know how to replace the characters and have the replaced string after the comparision is over in the for loop in my main.
    Currently , i am able to replace , but i am not able to have the replacements done in a single variable.
    The output of the code is
    e\u3006ame
    ena\u3005e
    But i want the output i require is,
    e\u3006a\u3005e
    Please offer some help in this regard
    import java.io.*;
    class Read1
         public static void main(String s[])
             String rp,snd;
             String tmp="ename";
             for(int i=0;i<tmp.length();i++)
                 snd=getCodepoint(tmp.charAt(i));
                 if(snd!=null)
                    rp=replace(tmp,String.valueOf(tmp.charAt(i)),"\\u"+snd);
                    System.out.println(rp);
    public static String replace(String source, String pattern, String replace)
         if (source!=null)
             final int len = pattern.length();
             StringBuffer sb = new StringBuffer();
             int found = -1;
             int start = 0;
             while( (found = source.indexOf(pattern, start) ) != -1)
                 sb.append(source.substring(start, found));
                 sb.append(replace);
                 start = found + len;
             sb.append(source.substring(start));
             return sb.toString();
         else return "";
    ...,Any help in this regard would be useful
    Thanks
    khurram

    This manual replacement thingy reminds me of quite an old technique, when
    64KB of memory was considered enough for 20 users (at the same time that is!)
    Suppose you have a buffer of, say, n characters. Starting at location i, a region
    of chars have to be swapped with bytes starting at location j >= i+l_i; the lengths
    of the two regions are l_i and l_j respectively.
    Suppose the following method is available:public void reverse(char[] buffer, int f, int l_f) {
       for (int t= f+l_f; --t > f; f++) {
          char tmp=buffer[f]; buffer[f]= buffer[t]; buffer[t]= tmp;
    }i.e. the above method reverses a region of characters, starting at position f
    with length l_f. Given this simple method, the original problem can be solved
    using the following simple sequence:reverse(buffer, i, j+l_j);
    reverse(buffer, i, l_j);
    reverse(buffer, i+l_j, j-i-l_i);
    reverse(buffer, j+l_j-l_i, l_i);Of course, when replacing characters we don't need the last reversal.
    kind regards,
    Jos (dinosaurus)

  • Lua function to replace metatags in a string?

    (Maybe this is a recipe request for the new cookbook site.)
    I'd like a function that, given a string and a LrPhoto, will search and replace tags in the string with metadata from the photo. So, given a string 'The title of this photo is {{title}}', it would return a string where {{title}} has been replaced with the LrPhoto.getRawMetadata('title') (or maybe getFormattedMetadata). I'm sure it's been written more than once. Is there one out there to be shared before I write my own?
    db

    I spent the time on this myself and don't know why I bothered asking, it was so simple. Here's what I did. First, a general-purpose function to replace any token in a string with values from a table:
    -- replace any string of characters in a string that are surrounded by curly
    -- braces (e.g. {foo}) with the value in the table corresponding to 'foo'.
    -- will replace all tokens in braces if there are more than one
    function DFB.replaceTokens( tokenTable, str )
        return str:gsub( '{(.-)}', function( token ) return tokenTable[token] end )
    end
    Then, if you want to do this with a photo's metadata, just pass the table that's returned from getRaw/FormattedMetadata:
    line = DFB.replaceTokens(  photo:getFormattedMetadata( nil ) , line )
    So if line starts out with "my caption is {caption}" and the photo's caption is 'My Photo Caption', the result is "my caption is My Photo Caption".
    I use this in a simple templating system that reads an HTML template from a file and does this for each line as it reads/writes it. Works well.

  • Replacing substrings in a string.

    I have three strings.
    String one
    String two
    String three
    String one is a substring occuring somewhere in String three.
    I want to replace String one occuring in String three with String two.
    How can i do this.
    Please help.

    Hi ,
    you cannot replace the String but you can get the replaced String
    for more information see the following links
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#replace(char, char)
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#replaceAll(java.lang.String, java.lang.String)
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#replaceFirst(java.lang.String, java.lang.String)
    API in String class is
    1. String replace(char oldChar, char newChar)
    2. String replaceAll(String regex, String replacement)
    3. String replaceFirst(String regex, String replacement)
    the above three API returns the result but the original string cannot be changed.
    If you want to change the original string use StringBuffer instead of String. for more detail for StringBuffer is see the following link
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/StringBuffer.html

  • Replacing 'word' in a string

    Hi! I want to replace Strings in a String, but if the the substring which has to be replaced is not a word, then i don't want it to be replaced. Eg.: I want to replace Words for other strings, where words are not substring of other Words :)
    Just want to ask if someone has made this before, and can help me out
    cu
    athalay

    But, my original question wasn't this. I
    want to replace words(string) for other strings in
    sentences(string). I hope it's clearer. So for example
    I have a sentence: This is an applepie. And if I want
    to replace apple for pear, then do not replace this
    sentence for pearpie, just remain it, because there's
    no "apple" word in this sentence. I hope it's clearer.
    My main problem is, that handling the First word of
    the sentence. It easy to replace " "+word+" " for what
    I want, but there are separatorchars like , . etc :)Search for the word you want to replace. Once you have found it, you will need to do a series of other checks...
    1) is it at the beginning or end of the sentence? (then you need to look at the character before or after the word depending on location in entire String to see if it is whitespace or separator character)
    2) is it surrounded by whitespace or separator characters on both sides? (get the surrounding characters and compare to a list of acceptable characters to make this a word, ie " ", ",", ";"...
    Only replace words that pass the conditions (beginning of sentence and followed by whitespace or separator, end of sentence and preceeded by whitespace or separator, or middle of sentence and surrounded by whitespace or separators).

  • Replace a string with another string in a file

    I have to replace a string with another string. Say for example in a html file it got a line like,
    <a href="##"></a>
    now i want to replace this ## with the full derived path like
    "c;\\sample folder\\sample subfolder\\samplefile.html"
    can someone help me to do this?
    pls tell me from the file opening till closing the file.

    I have to replace a string with another string. Say
    for example in a html file it got a line like,
    <a href="##"></a>
    now i want to replace this ## with the full derived
    path like
    "c;\\sample folder\\samplesubfolder\\samplefile.html"
    can someone help me to do this?
    pls tell me from the file opening till closing the
    file.
    public class Buckel {
      final static String CONST = "c:\\sample folder\\samplesubfolder\\samplefile.html";
      public Buckel() {
      public static void main ( String[] argv )  throws Exception {
        int    idx = 0;
        String in  = "<a href=\"##\"></a>",   // We'll imagine this just gets here somehow. If it's on the i/p file then take the '\' out B4 and aft the '##'.
               out = "";
        idx = in.indexOf( "##" );
        if ( idx > 0 ) {
          out = in.substring( 0, idx ) + CONST + in.substring( idx+=2, in.length() );
        System.out.println( out );
    }

  • How to use replace(CharacterSequence, CharacterSequence) in String class

    Need simple java program using the following
    how to use replace(CharacterSequence, CharacterSequence) in String class
    Kindly help

    From http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#replace(java.lang.CharSequence,%20java.lang.CharSequence)
    replace
    public String replace(CharSequence target,
    CharSequence replacement)Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. The replacement proceeds from the beginning of the string to the end, for example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab".
    Parameters:
    target - The sequence of char values to be replaced
    replacement - The replacement sequence of char values
    Returns:
    The resulting string
    Throws:
    NullPointerException - if target or replacement is null.
    Since:
    1.5

  • CS3: grep search to replace part of a string

    Can I do a grep search for a string of text but only replace a portion of the string while leaving the remainder intact?
    iMac G5, OS 10.5.5

    In addition to Eric:
    Find "some search string", Replace "some replacement string " also replaces part of the string, not touching anything...
    But the GREP search has two advantages: First, if you define formatting in the Replace field (italics, superscript, a character style), only the 'search'/'replacement' part will be affected, rather than the entire found string (as in regular search).
    The second big advantage is you can use any regular GREP single character wildcard in the 'left' and 'right' (matching-but-not-marking) parts. A few useful examples: '\d' (digit), '\l' and '\u' (lowercase and uppercase), '.' (any character), or even '[a-f]' (lowercase 'a' to 'f'). The only limitation is that you cannot use the once, zero-or-more, or once-or-more modifiers -- the strings must have a fixed length. FYI, those three modifiers are, respectively, ?, *, and +.
    This restriction does not apply to the 'middle' string, the one you are going to replace anyway -- use whatever GREP you want.

  • Replace frist in html string

    Hi Guys,
    I have an html string defined in property file.<html>,,,,,,<body>,,,,,blah blah $1 blah blah .........</html>
    I have html and eg $1, $2 so on.
    I want to replace $1 with another string value in the program, I tried str.replaceFirst("\\$1",string);
    but didnt work,
    please help me replcing it,
    thanks,

    DrClap wrote:
    It didn't work because that method takes a regular expression as its first parameter. (The API documentation does mention that fact.) The regular expression you passed it ("$1") ...The OP did escape the $, but &#92;&#92; get eaten by the forum software as a new-line char.
    @OP, the replaceFirst(...) returns a new String (and does not change the original String!), so you will have to do:
    String s = "<html>,,,,,,<body>,,,,,blah blah $1 blah blah .........</html>";
    s = s.replaceFirst("\\$1", "XYZ");

  • Covert String Array to String

    Hey,
    I have this code that take a string
    EX:
    Straw? No, too stupid a fad, I put soot on warts
    and takes out the "?" and "," and places a space in their spot, then tokenizes the string so now all the spaces are gone (right?) then places the tokenized string into and array. Now I want that array into a string.
    Pretty much what I want to go from is
    this:
    Straw? No, too stupid a fad, I put soot on warts
    to:
    StrawNotoostupidafadIputsootonwarts
    here is my code
    import java.util.*;
    public class TrivialApplication {
         public static void main(String args[])
              System.out.println( "Hello World!\n" );
              String hello = "Straw? No, too stupid a fad, I put soot on warts";
              hello = hello.replace('?',' ');
              hello = hello.replace(',',' ');
              StringTokenizer tokenizer = new StringTokenizer(hello);
              String[] array = new String[hello.length()];
              System.out.println(tokenizer.countTokens());
              System.out.println(hello.length());
              int count = tokenizer.countTokens();
              int x = 0;
              while(tokenizer.hasMoreTokens())
                   array[x] = tokenizer.nextToken();
                   x++;
    }

    Sweet thanks man here is the finished code. I took out the array because it was now not needed.
    import java.util.*;
    public class TrivialApplication {
         public static void main(String args[])
              System.out.println( "Hello World!\n" );
              String hello = "Straw? No, too stupid a fad, I put soot on warts";
              System.out.println(hello + "\n");
              hello = hello.replace('?',' ');
              hello = hello.replace(',',' ');
              StringTokenizer tokenizer = new StringTokenizer(hello);
              StringBuffer buffer = new StringBuffer();
              int count = tokenizer.countTokens();
              while(tokenizer.hasMoreTokens())
                   buffer = buffer.append(tokenizer.nextToken());     
              hello = buffer.toString();
              System.out.println("New String with changes \n");
              System.out.println(hello);
    [\code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Search string-1 in string-2 gives wrong results.

    Hi,
    I am searching for the string 'COM' in the sentence
    below.
    I am getting the string positons of string "COM"
    as 1 and 16.
    It Should be 1 and 19.
    thanks
    sharath
    SET SERVEROUTPUT ON
    DECLARE
    str VARCHAR2(200):='COM-1 Hello world COM-1 speaking';
    pos NUMBER ;
    ps NUMBER :=0 ;
    srch VARCHAR2(20) :='COM' ;
    BEGIN
    While( ps <= length(str))
    Loop
    pos := instr(str,srch);
    If pos > 0 then -- found string COM
    str := substr(str,pos + length(srch));
    dbms_output.put_line('COM found in pos ==> ' || pos );
    End If;
    ps := ps + 1;
    END LOOP;
    END;

    I believe the problem is that you are redefining the variable str within your loop. Once you find the first occurrence of "COM" in the string, you modify the string to remove that occurrence and then search again. The logic of your stored procedure is
    Loop 1:
    str = "COM-1 Hello world COM-1 speaking"
    - first occurrence of COM is at position 1
    Loop 2:
    str = "-1 Hello world COM-1 speaking"
    - first occurrence of COM is at position 16 in this new string
    Since you are removing the first three characters of the string when you call substr at the beginning of the second loop, you're looking for the position of "COM" in a slightly different string the second time around, hence the confusion.
    If you want to find the position in the original string, you'd want something like
    CREATE OR REPLACE PROCEDURE findOccurrence( string IN varchar2, search IN varchar2, offset IN number)
    AS
      currentPosition NUMBER;
    BEGIN
      currentPosition := INSTR( string, search );
      IF( currentPosition > 0 )
      THEN
        dbms_output.put_line( 'Search string found at position ==> ' || to_char(currentPosition+offset));
        findOccurrence( substr( string, currentPosition+length(search) ),
                        search,
                        currentPosition+length(search)+offset-1 );
      END IF;
    END;
    scott@jcave > exec findOccurrence( 'COM COM COM', 'COM', 0 );
    Search string found at position ==> 1
    Search string found at position ==> 5
    Search string found at position ==> 9
    PL/SQL procedure successfully completed.Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

Maybe you are looking for