Replacing string

Hello
How can I replace multiple string occurances in a string with some incremental number. for example, I want to replace the 1st occurrance with 1, the 2nd with 2 and so on.
thanks
pauli

public class replaceChar{
public void replaceChar(){}
public String replaceChar(String str, char c){
StringBuffer strBuffer=new StringBuffer(str);
int lenStrBuffer=strBuffer.length();
for(int i=0, l=1; i<lenStrBuffer; i++)
if(strBuffer.charAt(i)==c){
strBuffer.setCharAt(i, ((Integer.toString(l)).toCharArray())[0]);
l++;
System.out.println(strBuffer.toString());
return strBuffer.toString();
public static void main(String[] args){
String str="StringBuffer";
char c='r';//char to replace
replaceChar replacechar=new replaceChar();
replacechar.replaceChar(str, c);
}

Similar Messages

  • Search and replace strings in a file while ignoring substrings

    Hi:
    I have a java program that searches and replaces strings in a file. It makes a new copy of the file, searches for a string in the copy, replaces the string and renames the new copy to the original file, thereafter deleting the copy.
    Now searching for "abcd", for eg works fine, but searching for "Topabcd" and replacing it doesnot work because there is a match for "abcd" in a different search scenario. How can I modify the code such that if "abcd" is already searched and replaced then it should not be searched for again or rather search for "abcd" as entire string and not if its a substring of another string.
    In the below code output, all instances of "abcd" and the ones of "Topabcd" are replaced by ABCDEFG and TopABCDEF respectively, whereas according to the desired output, "abcd" should be replaced by ABCDEFG and "Topabcd" should be replaced by REPLACEMEFIRST.
    try
              String find_productstring = "abcd";
              String replacement_productstring = "ABCDEFG";
              compsXml = new FileReader(compsLoc);
              compsConfigFile = new BufferedReader(compsXml);
              File compsFile =new File("file.xml");
              File compsNewFile =new File("file1.xml");
              BufferedWriter out =new BufferedWriter(new FileWriter("file1.xml"));
              while ((compsLine = compsConfigFile.readLine()) != null)
                    new_compsLine =compsLine.replaceFirst(find_productstring, replacement_productstring);
                    out.write(new_compsLine);
                    out.write("\n");
                out.close();
                compsConfigFile.close();
                compsFile.delete();
                compsNewFile.renameTo(compsFile);
            catch (IOException e)
            //since "Topabcd" contains "abcd", which is the search above and hence the string "Topabcd" is not replaced correctly
             try
                   String find_producttopstring = "Topabcd";
                   String replacement_producttopstring = "REPLACEMEFIRST";
                   compsXml = new FileReader(compsLoc);
                   compsConfigFile = new BufferedReader(compsXml);
                   File compsFile =new File("file.xml");
                   File compsNewFile =new File("file1.xml");
                   BufferedWriter out =new BufferedWriter(new FileWriter("file1.xml"));
                   while ((compsLine = compsConfigFile.readLine()) != null)
                         new_compsLine =compsLine.replaceFirst(find_producttopstring, replacement_producttopstring);
                         out.write(new_compsLine);
                         out.write("\n");
                     out.close();
                     compsConfigFile.close();
                     compsFile.delete();
                     compsNewFile.renameTo(compsFile);
                 catch (IOException e)
            }Thanks a lot!

    Hi:
    I have a java program that searches and replaces
    strings in a file. It makes a new copy of the file,
    searches for a string in the copy, replaces the
    string and renames the new copy to the original file,
    thereafter deleting the copy.
    Now searching for "abcd", for eg works fine, but
    searching for "Topabcd" and replacing it doesnot work
    because there is a match for "abcd" in a different
    search scenario. How can I modify the code such that
    if "abcd" is already searched and replaced then it
    should not be searched for again or rather search for
    "abcd" as entire string and not if its a substring of
    another string.
    In the below code output, all instances of "abcd" and
    the ones of "Topabcd" are replaced by ABCDEFG and
    TopABCDEF respectively, whereas according to the
    desired output, "abcd" should be replaced by ABCDEFG
    and "Topabcd" should be replaced by REPLACEMEFIRST.
    try
    String find_productstring = "abcd";
    String replacement_productstring = "ABCDEFG";
    compsXml = new FileReader(compsLoc);
    compsConfigFile = new
    BufferedReader(compsXml);
    File compsFile =new File("file.xml");
    File compsNewFile =new File("file1.xml");
    BufferedWriter out =new BufferedWriter(new
    FileWriter("file1.xml"));
    while ((compsLine =
    compsConfigFile.readLine()) != null)
    new_compsLine
    =compsLine.replaceFirst(find_productstring,
    replacement_productstring);
    out.write(new_compsLine);
    out.write("\n");
    out.close();
    compsConfigFile.close();
    compsFile.delete();
    compsNewFile.renameTo(compsFile);
    catch (IOException e)
    //since "Topabcd" contains "abcd", which is
    the search above and hence the string "Topabcd" is
    not replaced correctly
    try
                   String find_producttopstring = "Topabcd";
    String replacement_producttopstring =
    topstring = "REPLACEMEFIRST";
                   compsXml = new FileReader(compsLoc);
    compsConfigFile = new
    gFile = new BufferedReader(compsXml);
                   File compsFile =new File("file.xml");
                   File compsNewFile =new File("file1.xml");
    BufferedWriter out =new BufferedWriter(new
    dWriter(new FileWriter("file1.xml"));
    while ((compsLine =
    compsLine = compsConfigFile.readLine()) != null)
    new_compsLine
    new_compsLine
    =compsLine.replaceFirst(find_producttopstring,
    replacement_producttopstring);
    out.write(new_compsLine);
    out.write("\n");
    out.close();
    compsConfigFile.close();
    compsFile.delete();
    compsNewFile.renameTo(compsFile);
                 catch (IOException e)
    Thanks a lot!I tried the matches(...) method but it doesnt seem to work.
    while ((compsLine = compsConfigFile.readLine()) != null)
    if(compsLine.matches(find_productstring))
         System.out.println("Exact match is found for abcd");
         new_compsLine =compsLine.replaceFirst(find_productstring, replacement_productstring);
    out.write(new_compsLine);
    out.write("\n");
         else
         System.out.println("Exact match is not found for abcd");
         out.write(compsLine);
         out.write("\n");

  • Search and replace string not work as per required

    please find the attachment. i am trying to replace the variable names but it doesnt replace the variable as i expected. Please help me in this
    Attachments:
    Replace String.vi ‏8 KB
    Replace String.vi ‏8 KB

    You haven't configured the strings to be "default". Hence, all string elements in your attached vi's are empty.
    I have no idea what you try to achieve without those strings....
    Norbert 
    CEO: What exactly is stopping us from doing this?
    Expert: Geometry
    Marketing Manager: Just ignore it.

  • Search and replace string formatting

    Hi,
    I am trying to do a search and replace formatting of a string.
    In the example I am looking for string "PASSED" but it must also start with usbflash and some number + PASSED.
    I can't get the format to have a number from 1-99. The number of replacements should add up to 6 in this case. I have tried with \d for any number, and I also tried [1-99].
    Solved!
    Go to Solution.

    Right click on the Search And Replace String function.  There is an option to use Regular Expressions.  Then give this a try.
    EDIT: You will need to set the Replace All input to TRUE.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines
    Attachments:
    Match Pattern.png ‏12 KB

  • Search and replace string problems

    Hi to all,
    I have problem with Search and replace string function. It shows me a wrong Value (Number) from 15 to 100 is everything OK (15=0, 30=1, 45=2, 100=3), but after 100 ........
    Take look in VI and if you have any ideas post them please
    THX
    Igor 
    Attachments:
    indexing.vi ‏10 KB

    there will be no 15115 string, but 15 or 115 and 15 is 0, 115 is 4. Anyway, i have changed string input format and now its working THX for your help
    Attachments:
    indexing.vi ‏10 KB

  • Search and Replace String throwing the wrong error message with regexp?

    This came up in a LAVA thread, and I'm not sure if there's a bug here or not. When using Search and Replace string, and using a regular expression of [(G[b|i])], LabVIEW throws error -4622, "There is an unmatched parenthesis in a regular expression."  There are obviously no unmatched parenthesis in that expression, so it seems to me that the wrong error is being thrown. I'm just not sure if that's a syntactically valid regexp. The problem seems to be with nesting [ ]'s inside ( )'s inside [ ]'s. I've tried a couple of regexp resources on the Web, and one suggests it's valid, while the other seems to think it isn't.
    Message Edited by eaolson on 03-13-2007 10:33 AM
    Attachments:
    ATML_StandardUnit2.vi ‏10 KB
    regexp.png ‏5 KB

    adambrewster wrote:
    I think your regexp is invalid.
    In regexps, brackets are not the same as parentheses.  Parens are for grouping, while brackets are for matching one of a class of characters.  Brackets can not be nested.
    If the regexp is replaced with [G[bi]], there is no error, so it's not a matter of nested brackets. I couldn't find anything on the PCRE man page that forbids nested brackets specifically, but it makes sense.
    Your expression "[(G[bi])]", therefore parses as a character class which matches '(', 'G', '[', 'b', or 'i' followed by an unmatched paren, and an unmatched bracket.
    I don't believe that's the case. Replace the regexp with [(Gbi)], and the error goes away. So it's not a matter of the '(' being literal, and then encountering a ')' without a matching '('.
    daveTW wrote:
    what string exactly you want to replace? I think the round braces are not right in this case, since they mark partial matches which are given back by "match regular expression". But you don't want to extract parts of the string, you want to replace them (or delete, with empty <replace string>). So if you leave the outer [( ... )] then your RegEx means all strings with either "Gb" or "Gi".
    It's not my regular expression. A poster at LAVA was having problems with one of his (a truly frightening one), and this seemed to be the element that was causing the problem. I'm pretty sure that the originator of the regexp meant to use G(b|i), which seems like a complicated way of matching "Gb" or "Gi", if you ask me.

  • Search and replace string function

    Hello, I am using the "search and replace string" function and it does nt seem to work consistently for me.   I am using it in a situation where I am taking an array of strings, converting this into a spreadsheet string then deleting all of the commas.  Has anyone experienced the same behavior? I have searched through other posts and found other simular faults but none of the fixes worked for this. I can post the code it needed.
    Thanks,
    Andrew

    I agree that commas are often not desirable, especially if your software should also work in countries where comma is used as a decimal seperator.
    Where are the commas coming from? Does (1) each element of the original array have one (or more), do you (2) use comma as seperator if you convert it to a spreadhseet string?
    For (1), you might just strip out the comma for each element right in the loop. For case (2) you would simply use a different separator to begin with, of course.
    Btw: you are abusing a WHILE loop as a FOR loop, because you have a fixed number of iterations. Please replace it with a FOR loop. If you use a FOR loop, LabVIEW can manage memory much more efficiently, because it can allocate the entire output array before the loop starts. For While loops, the total number of iterations is not known to the compiler. (Of course a real program would also stop the loop if an error occurs. In this case you would need to stay woth the WHILE loop. )
    Do you have a simple example how the raw array elements look like. How many commas are there?
    LabVIEW Champion . Do more with less code and in less time .

  • Flash Charts - How to manipulate the #data# replacement string in XML

    I have a problem with the XML file for a flash chart. I am trying to display a 2dColumn chart of an SQL query with the general form:
    select null link, x as name, sum(y) as value from z group by (x);
    this generates multiple rows, which are displayed as a bar in the chart. So far so good. The problem is, that each row is defined as a block in the chart, but only one name entry is created "value", which is displayed in the legend of the chart.
    I can display the block names on the x-axis of the chart, however, I can't rotate them, so that they don't overlap in the display, which I would be able to do with names. I assume, that the blocks are defined in the #data# replacement string of the XML file. I would like to change the generated XML replacement string from the SQL to make each row selected a different name, and only have one block ("value").
    What would be the easiest way to achieve this?

    user587996,
    There's no way to manipulate the #data# replacement directly, but you could generate your own XML (see Re: Apex changing nulls to zeroes when creating Flash Charts for one way to do it).
    When you say "I can't rotate them, so that they don't overlap in the display" -- have you tried the Labels Rotation chart attribute, or is that not working?
    - Marco

  • Replace string in a file

    I want a java program can replace string in a file with given string.
    for example,
    my file is
    abc 100
    aaa 110
    ded 123
    replace aaa with mmm.
    my codes is reading line by line and looking for aaa ,if read_line.index("aaa")> -1,then write mmm and aaa.substring
    Do you have ant other solutions?is there any file class method I can use?
    cheers.

    String content = <get file content>;
    String newContent = content.replaceAll( "aaa", "I get my homework on java.sun.com" );
    if( !newContent.equals(content) )
       <rewrite file contents>

  • Accessing a JSTL variable in a JSP Scriptlet (need to replace string )

    I have
    <c:set var="myVar" value="..." />
    I need to replace single quotes and double quotes to be escaped because I pass them into javascript functions and set them as ID for div sections
    ... onclick ="func('${myVar}')" ..
    <div id="${myVar}">
    but if the string contains ' single quotes it messes up the javascript or double quotes messes up the ID portion of the HTML tag
    I know there is the JSTL function fn but I can't figure out how to do it properly in JSTL
    <c:set var="myVar"
    value="${fn:replace(myVar, "'", "\"")"/>
    But that gets tricky since the value portion is enclosed in quotes
    So I was thinking of using a Scriptlet part instead.

A: Accessing a JSTL variable in a JSP Scriptlet (need to replace string )

escaping quotes within quotes within quotes.... ARGH!
Recipe for a headache if ever there was one.
However you must be strong and resist the temptations of the dark side (Scriptlet code)
My suggestion for cleaning this up - write your own static function for escaping javascript strings.
public static String escapeJavascriptString(String s){
  return .......
}Then define the function in a tld:
<function>
    <description>
      Escapes a string for javascript purposes
    </description>
    <name>escapeJavascript</name>
    <function-class>com.mypackage.ELFunctions</function-class>
    <function-signature>java.lang.String escapeJavascript(java.lang.String)</function-signature>
    <example>
      <c:out value="${myfunc:escapeJavascript(name)}">
    </example>
  </function>Cheers,
evnafets

escaping quotes within quotes within quotes.... ARGH!
Recipe for a headache if ever there was one.
However you must be strong and resist the temptations of the dark side (Scriptlet code)
My suggestion for cleaning this up - write your own static function for escaping javascript strings.
public static String escapeJavascriptString(String s){
  return .......
}Then define the function in a tld:
<function>
    <description>
      Escapes a string for javascript purposes
    </description>
    <name>escapeJavascript</name>
    <function-class>com.mypackage.ELFunctions</function-class>
    <function-signature>java.lang.String escapeJavascript(java.lang.String)</function-signature>
    <example>
      <c:out value="${myfunc:escapeJavascript(name)}">
    </example>
  </function>Cheers,
evnafets

  • Replace String

    how can we replace a char of subsrting with in a string
    e.g we have " Today is [Date] ......."
    i want to replace [Date] with todays date

    Here is a method to do it. Using indexOf and substring is actually faster than going through each character using startsWith as seen in some other implementations.
          * Replace occurances of a String with another.
          * This will replace all instances of 'Old' in 'S' with 'New'. The source
          * String is not modified.
          @param S Source String
          @param Old String to replace
          @param New String to put in the place of 'Old'
          @return String with replacements made.
         public static String replace(String S, String Old, String New)
              if( (S == null) || (Old == null) )
                   return S;
              StringBuffer B = new StringBuffer();
              int i = 0;
              int length = S.length();
              int size = Old.length();
              if(size == 0)
                   return S;
              while(i < length)
                   int q = S.indexOf(Old,i);
                   if( q < 0 ) //- There are no more occurences of the substring
                        B.append(S.substring(i));
                        i = length;
                   else //- q is the next occurence of Old
                        B.append(S.substring(i,q)); //- the part before Old
                        B.append(New);
                        i = q + size;
              return B.toString();
         }

  • Latest iTunes update spams my console messages with this: Failed to create replacement string

    iTunes seems to work, but I keep getting this message when I open and close the program. Any ideas as to why?

    I get the same message. Anyone have a fix for this yet? Just installed iTunes update today, 9/20, and console is spammed with hundreds of these messages - Failed to create replacement string".
    MBA mid 2012. on latest Mavericks, have not installed iOS8 on anything yet.

  • Help with REGEXP_REPLACE upper replacement string

    Hi All,
    I am attempting to uppercase the replacement string from my reg expression without success:
    SELECT regexp_replace('src=/i/uie_v2/js','(/uie_v2/)',upper('\1')) from dual
    returns 'src=/i/uie_v2/js'
    I understand that upper cannot be used .. just showing as an example. Any ideas on how to achieve this ?
    Thanks in advance :)
    Greg

    >
    I need a way of using a search pattern that goes from the first double quote to the last slashThis can be achieved as below
    SQL> select str,regexp_substr(str,'"/([^"]*?/){1,}',1) res
      2  from testdata;
    STR                                                     RES
    <link rel="stylesheet" type="text/css" href="/i/uie_V2/ "/i/uie_V2/ext-3.0.0/resources/css/
    ext-3.0.0/resources/css/ext-all-uie.css">
    <script src="/i/uiE_v2/js/bob/bobsFile.js"></script>
    <script src="/i/UIE_v2/js/fred/fredsFile.js"></script>
    <script src="/i/uiE_v2/js/john/johnsFile.js"></script>
    <link rel="stylesheet" type="text/css" href="/i/uie_V2/ "/i/uie_V2/ext-3.0.0/resources/css/
    ext-3.0.0/resources/css/ext-all-uie.css">
    <script src="/i/uiE_v2/js/bob/bobsFile.js"></script>
    <script src="/i/UIE_v2/js/fred/fredsFile.js"></script>
    <script src="/i/uiE_v2/js/john/johnsFile.js"></script>For achieving yor replace, can we use PL/SQL as below?
    I think the same thing can be achieved using CONNECT BY..SYS_CONNECT_BY_PATH or Recursion. But PL/SQL seems to be better.
    And we can wait for a MODEL solution..
    SQL> create or replace function f1(p_str varchar2) return varchar2 is
      2    lc_str varchar2(4000) := p_str;
      3    ln_count number := 1;
      4  begin
      5    while regexp_substr(lc_str,'"/([^"]*?/){1,}',ln_count) is not null loop
      6      lc_str := regexp_replace(lc_str,'"/([^"]*?/){1,}',
      7          lower(regexp_substr(lc_str,'"/([^"]*?/){1,}',1,ln_count)),1,ln_count);
      8      ln_count := ln_count + 1;
      9    end loop;
    10    return lc_str;
    11  end f1;
    12  /
    Function created.
    SQL> select str,f1(str) res
      2  from testdata;
    STR                                                     RES
    <link rel="stylesheet" type="text/css" href="/i/uie_V2/ <link rel="stylesheet" type="text/css" href="/i/uie_v2/
    ext-3.0.0/resources/css/ext-all-uie.css">               ext-3.0.0/resources/css/ext-all-uie.css">
    <script src="/i/uiE_v2/js/bob/bobsFile.js"></script>    <script src="/i/uie_v2/js/bob/bobsFile.js"></script>
    <script src="/i/UIE_v2/js/fred/fredsFile.js"></script>  <script src="/i/uie_v2/js/fred/fredsFile.js"></script>
    <script src="/i/uiE_v2/js/john/johnsFile.js"></script>  <script src="/i/uie_v2/js/john/johnsFile.js"></script>
    <link rel="stylesheet" type="text/css" href="/i/uie_V2/ <link rel="stylesheet" type="text/css" href="/i/uie_v2/
    ext-3.0.0/resources/css/ext-all-uie.css">               ext-3.0.0/resources/css/ext-all-uie.css">
    <script src="/i/uiE_v2/js/bob/bobsFile.js"></script>    <script src="/i/uie_v2/js/bob/bobsFile.js"></script>
    <script src="/i/UIE_v2/js/fred/fredsFile.js"></script>  <script src="/i/uie_v2/js/fred/fredsFile.js"></script>
    <script src="/i/uiE_v2/js/john/johnsFile.js"></script>  <script src="/i/uie_v2/js/john/johnsFile.js"></script>Edited by: jeneesh on Oct 5, 2012 9:37 AM
    Not rigorously tested

  • Replacing Strings (again)

    Hallo,
    I have a string with lots of numbers in scientific notation, e.g. 1,23456E+10 (German OS). I want to save it to a spreadsheat file, but before that I want to replace all "," with "." and all "E" with "e". (Otherwise GNUplot cannot read them).
    With my idea and the ideas of the LabVIEW-Forum, only the first ones were replaced.
    Example: 1,0E-6 1,0E-6 becomes 1.0e-6 1,0E-6 and NOT 1.0e-6 1.0e-6
    How can I manage that? The common "Search and Replace String" works but stops after the first match.
    Arno
    PS: Please send VI's that can be loaded with LabVIEW 6.1^.
    Arno
    Please help me, thank you !!
    Arno
    PS: I am using LabVIEW 6.1."

    The E-->e is easy, just use "to lower case". :-)
    To replace all using search and replace, just wire a TRUE to the "replace all?" terminal.
    The attached example in LV6.1 shows both methods.
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    Format4GNUPlot.vi ‏21 KB

  • Endeca Pipeline REPLACEMENT string

    HI
    <EXPRESSION LABEL="" NAME="UPDATE" TYPE="VOID" URL="">
    <EXPRNODE NAME="PROP_NAME" VALUE="NEW_PRODUCT"/>
    <EXPRESSION LABEL="" NAME="REPLACE" TYPE="STRING" URL="">
    <EXPRNODE NAME="TARGET" VALUE="Y"/>
    <EXPRNODE NAME="*REPLACEMENT*" VALUE="N"/>
    <EXPRESSION LABEL="" NAME="IDENTITY" TYPE="PROPERTY" URL="">
    <EXPRNODE NAME="PROP_NAME" VALUE="NEW_PRODUCT"/>
    </EXPRESSION>
    </EXPRESSION>
    </EXPRESSION>
    </EXPRESSION>
    I need to assign a property value for the REPLACEMENT string.. that is "PRODUCT" which is specified below for
    <EXPRESSION LABEL="" NAME="UPDATE" TYPE="VOID" URL="">
    <EXPRNODE NAME="PROP_NAME" VALUE="PRODUCT"/>
    <EXPRESSION LABEL="" NAME="CONCAT" TYPE="STRING" URL="">
    <EXPRESSION LABEL="" NAME="IDENTITY" TYPE="PROPERTY" URL="">
    <EXPRNODE NAME="PROP_NAME" VALUE="PACKAGE_OUTLINE_NAME"/>
    </EXPRESSION>
    <EXPRESSION LABEL="" NAME="CONST" TYPE="STRING" URL="">
    <EXPRNODE NAME="VALUE" VALUE=" - "/>
    </EXPRESSION>
    <EXPRESSION LABEL="" NAME="IDENTITY" TYPE="PROPERTY" URL="">
    <EXPRNODE NAME="PROP_NAME" VALUE="Marketing Outline Description"/>
    </EXPRESSION>
    </EXPRESSION>
    looks like REPLACEMENT accept only CONST string..Can I assign a property value?
    </EXPRESSION>
    </EXPRESSION>

    Use the UPDATE expression, e.g. something like:
    <EXPRESSION TYPE="VOID" NAME="UPDATE">
    <EXPRNODE NAME="PROP_NAME" VALUE="NEW_PRODUCT"/>
    <EXPRESSION TYPE="PROPERTY" NAME="IDENTITY">
    <EXPRNODE NAME="PROP_NAME" VALUE="PRODUCT"/>
    </EXPRESSION>
    </EXPRESSION>
    Note it would have to appear after the creation of PRODUCT property (assuming this is dynamically created as shown in your example). If you need to make this conditional (i.e. only gets replaced if the value of NEW_PRODUCT is Y), then use an IF expression around it.
    Michael

  • How do i do a Advance replace string logic?

    Hi all,
    I have an issue on writing a logic to replace a string in a sentence
    Suppose i fill in 3 input
    1st input - *"The Name contains 'Test1' and 'Test2' and this is it"*
    2nd input - *"The Name contains \"{mercName1}\" and \"{mercName2}\" and this is it"*
    3rd input - *"(\"{mercName1}\")) and (\"{mercName2}\"))"*
    The logic will compare 1st input and 2nd input, then replace mercName1/mercName2, and the output should be like this
    output - *("'Test1'")) and ("'Test2'"))*
    Currently i have make it works and here's the logic
    public class ReplaceString {
         private String getRuleMap(String strRuleC_DRL, String strRuleM_Desc, String strRuleM_Map) {
              String[] strRuleC_DRL_split = strRuleC_DRL.split(" ");
              String[] strRuleM_Desc_split = strRuleM_Desc.split(" ");
              Map compareMap = new HashMap();
              if(strRuleC_DRL_split.length == strRuleM_Desc_split.length) {
                   for(int x=0; x<strRuleC_DRL_split.length; x++) {
                        int compare = strRuleC_DRL_split[x].compareTo(strRuleM_Desc_split[x]);
                        if(compare != 0) {
                             compareMap.put(strRuleM_Desc_split[x].replaceAll("\"", ""), strRuleC_DRL_split[x].replaceAll("\"", ""));
              if(!compareMap.isEmpty()) {
                   Iterator keyIter = compareMap.keySet().iterator();
                   while(keyIter.hasNext()) {
                        String theKey = keyIter.next().toString();
                        String theValue = compareMap.get(theKey).toString();
                        if(strRuleM_Map.indexOf(theKey) > 0) {
                             strRuleM_Map = this.replace(strRuleM_Map, theKey, theValue);
              return strRuleM_Map;
         private 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 "";
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              ReplaceString rs = new ReplaceString();
              System.out.println(rs.getRuleMap("The Name contains 'Test1' and 'Test2' and this is it", "The Name contains \"{mercName1}\" and \"{mercName2}\" and this is it", "(\"{mercName1}\")) and (\"{mercName2}\"))"));
    }Now, here's the problem, when i key in
    input - *"The Name contains 'Test1 and Test2' and 'Test3 and Test 4' and this is it"*
    i expect the output should be
    output - *("'Test1 and Test2'")) and ("'Test3 and Test4'"))*
    but i hit problem cause the string compare is only 1 to 1
    Is there any advice? Thanks

    You could try to use regular expressions?

  • Maybe you are looking for