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

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

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

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

  • Find & replace part of a string in Numbers using do shell script in AppleScript

    Hello,
    I would like to set a search-pattern with a wildcard in Applescript to find - for example - the pattern 'Table 1::$*$4' for use in a 'Search & Replace script'
    The dollar signs '$' seem to be a bit of problem (refers to fixed values in Numbers & to variables in Shell ...)
    Could anyone hand me a solution to this problem?
    The end-goal - for now - would be to change the reference to a row-number in a lot of cells (number '4' in the pattern above should finally be replaced by 5, 6, 7, ...)
    Thx.

    Hi,
    Here's how to do that:
    try
        tell application "Numbers" to tell front document to tell active sheet
            tell (first table whose selection range's class is range)
                set sr to selection range
                set f to text returned of (display dialog "Find this in selected cells in Numbers " default answer "" with title "Find-Replace Step 1" buttons {"Cancel", "Next"})
                if f = "" then return
                set r to text returned of (display dialog "Replace '" & f & "' with " default answer f with title "Find-Replace Step 2")
                set {f, r} to my escapeForSED(f, r) -- escape some chars, create back reference for sed
                set tc to count cells of sr
                tell sr to repeat with i from 1 to tc
                    tell (cell i) to try
                        set oVal to formula
                        if oVal is not missing value then set value to (my find_replace(oVal, f, r))
                    end try
                end repeat
            end tell
        end tell
    on error number n
        if n = -128 then return
        display dialog "Did you select cells?" buttons {"cancel"} with title "Oops!"
    end try
    on find_replace(t, f, r)
        do shell script "/usr/bin/sed 's~" & f & "~" & r & "~g' <<< " & (quoted form of t)
    end find_replace
    on escapeForSED(f, r)
        set tid to text item delimiters
        set text item delimiters to "*" -- the wildcard 
        set tc1 to count (text items of f)
        set tc2 to count (text items of r)
        set text item delimiters to tid
        if (tc1 - tc2) < 0 then
            display alert "The number of wildcard in the replacement string must be equal or less than the number of wildcard in the search string."
            error -128
        end if
        -- escape search string, and create back reference for each wildcard (the wildcard is a dot in sed) --> \\(.\\)
        set f to do shell script "/usr/bin/sed -e 's/[]~$.^|[]/\\\\&/g;s/\\*/\\\\(.\\\\)/g' <<<" & quoted form of f
        -- escape the replacement string, Perl replace wildcard by two backslash and an incremented integer, to get  the back reference --> \\1 \\2
        return {f, (do shell script "/usr/bin/sed -e 's/[]~$.^|[]/\\\\&/g' | /usr/bin/perl -pe '$n=1;s/\\*/\"\\\\\" . $n++/ge'<<<" & (quoted form of r))}
    end escapeForSED
    For what you want to do, you must have the wildcard in the same position in both string. --> find "Table 1::$*$3", replace "Table 1::$*$4"
    Important, you can use no wildcard in both (the search string and the replacement string) or you can use any wildcard in the search string with no wildcard in the replacement string).
    But, the number of wildcard in the replacement string must be equal or less than the number of wildcard in the search string.

  • How to replace special characters in string.

    Hello,
    I want to replace special characters such as , or ; with any other character or " ".I find out there is no such function is java for this.There is only replace() but it accepts only chars.If anybody know how to do this?.
    Thanks,

    Hello,
    I want to replace special characters such as , or ;
    with any other character or " ".I find out there is no
    such function is java for this.There is only replace()
    but it accepts only chars.If anybody know how to do
    this?.
    Thanks,Can't you just do the following?
    public class Test
         public static void main(String[] args)
         String testString = "Hi, there?";
         System.out.println(testString.replace(',',' '));
    }

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

  • How count the number of substrings in a string

    Hi all,
    I wonder if someone can help me and point out where I'm going wrong.
    I want to count the number of substring starting with 'd' and ending with 'e' in a string supplied by a user.
    currently my code is only counting the number of 'd' and 'e' characters in the string.
        public static void main (String [] args)
             Scanner input = new Scanner (System.in);
             String mstring;// string variable that the user will enter
             int i = 0; // upstep variable
             int count = 0; // int variable to count the number of substrings
             System.out.print("Enter a string: ");
             mstring = input.nextLine();
             while (i != mstring.length())
                       if(mstring.charAt(i)=='d'){count++;}
                       else if (mstring.charAt(i)=='e'){count++;}
                       i++;
             System.out.println("The total d e substrings is " + count);
    }For example if the user enters adbedeaadffe the total number of substrings should be 5 but I'm getting 6 as the program is just counting the number of times it comes across 'd' and 'e'
    Can anyone shed some light on this for me thanks.

    Hi all I had a good few replies to this question but they seem to have been removed from the system for some reason.
    I've changed my code slightly and it works but only for one round of the guard.
                   Scanner input = new Scanner (System.in)
             String mstring;// main string variable that the user will enter
             int i = 0;  // upstep variable
             int count = 0; // int variable to count the number of substrings
         System.out.print("Enter a string: ");
             mstring = input.nextLine();
             int y =mstring.length();
             while (i != mstring.length() && y !=0)
             if (mstring.charAt(i) == 'd' && mstring.charAt(y-1)=='e'){count = count+1;}
             y--;
             i++;
             System.out.println("The total a b substrings is " + (count));The above code will only print out one substring of adbedeaadffe but that is not what I need, I need to be able to print out all of the substrings.
    Can anyone tell me where I'm going wrong.
    Thanks in advance

  • Replace characters in a string

    Hi,
    I need to replace all occurrences of control characters except space,newline,tabs in a string . I can give a replace statement for each of these characters but I want to avoid this by making use of regular expressions. Can anyone help me in this regard.
    I tried using the following replace statements with regular expression, but i am not getting the required results:
    replace all occurrences of REGEX '[[:cntrl:]]' in lv_char with space replacement count lv_count_r.
    ---> this replaces even the spaces
    replace all occurrences of REGEX '[[:cntrl:]][^[:space:]]' in lv_char with space replacement count lv_count_r.
    --> this replaced even some alpha numeric characters
    Thanks and Regards,
    Shankar

    is there anyway to do this without using regular
    expressions.. regular expressions are the last
    solution for me..Remember that you can never really replace the characters of a String. Strings are immutable. Once created they cannot change.

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

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

  • Replacing a char with string in a string buffer.

    Hi all,
    I have a huge xml file. Need to search for the following characters: ^ & | \ and replace each character with \T\ \F\ \B\ \C\ respectively.
    i.e. ^ must be replaced with \T\
    & must be replaced with \F\
    I see that it can be done in case of String using replaceAll() but have no clue about achieving using the stringbuffer??
    Any help is higly appeciated.
    Thanks in advance.

    Hi all,
    I have a huge xml file. Need to search for the
    following characters: ^ & | \ and replace each
    character with \T\ \F\ \B\ \C\ respectively.
    i.e. ^ must be replaced with \T\
    & must be replaced with \F\
    I see that it can be done in case of String using
    replaceAll() but have no clue about achieving using
    the stringbuffer??
    Any help is higly appeciated.
    Thanks in advance.here the solution for your problem:
    example code as follows,
         StringBuffer stringBuffer = new StringBuffer("your xml content");           
                String xmlString = stringBuffer.toString();
                char[]  xmlCharArray =  new char[];
                xmlString.getChars(0, xmlString.length()-1, xmlCharArray, 0);
               StringBuffer alteredXmlBuf = new StringBuffer();
                for(int i=0; i<xmlCharArray.length; i++){
                               if( xmlCharArray[i] == '^'){
                                      alteredXmlBuf.append(" \\T\\") ;
                               }else if(xmlCharArray[i] == '&'){
                                      alteredXmlBuf.append(" \\F\\") ;
                               }else if(xmlCharArray[i] == '|'){
                                      alteredXmlBuf.append(" \\B\\") ;
                               }else if(xmlCharArray[i] == '\'){
                                      alteredXmlBuf.append(" \\C\\") ;
                               }else {
                                       alteredXmlBuf.append(xmlCharArray);
    now alteredXmlBuf StringBuffer object contains your solution.

Maybe you are looking for

  • Acrobat 7.0 and Windows 8

    Is Adobe Acrobat 7.0 Standard compatible with Windows 8?

  • How to get the difference between two columns in a column group

    Hi All, My first time here and really new to programming. I would like to get the difference between 2 columns that are inside  a column group. Here is my sample table below: The Column Group is PeriodNumber and can only choose 2. like 1 and 2.. I wo

  • How to update BLOB resource ???

    Hi, I've created BLOB resource successfully. But after my attempt to update it using UPDATE resource_view SET res=updatexml(res,'/Resource/Contents/*',blob_res) WHERE any_path= '/path'; I get an error ORA-06550: line 17, column 7: PL/SQL: ORA-00932:

  • How to start SAP and oracle on SUN SOLARIS SYSTEM

    hi. Please suggest (Mistakenly we restarted the server when SAP is on and now SAP is not starting) 1. How to start the SAP ECC6 in sun Solaris.(version 10) 2.How to start the oracle in sun Solaris (version 10) We are trying with  sh startsap SID but

  • New Drives - boot Neo4 Platinum from SATA II?

    I am going to re-configure my AMD 64 3200+ K8N Neo4 Platinum mobo to have 2 Hitachi T7K250 SATA II hard drives (currently PC has a single IDE drive that will be removed).  I have XP PRO original as well as SP2 on a separate disc. Can anyone suggest a