Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple string replacements without affecting substituted text in subsequent iterations

Tags:

java

I've posted about letters earlier, but this is an another topic, I have a json response that contain 2 objects, from and to , from is what to change, and to is what it will be changed to .

My code is :

// for example, the EnteredText is "ab b test a b" .
EnteredString = EnteredText.getText().toString();
for (int i = 0; i < m_jArry.length(); i++) {
    JSONObject jo_inside = m_jArry.getJSONObject(i);

    String Original = jo_inside.getString("from");
    String To = jo_inside.getString("to");

    if(isMethodConvertingIn){
        EnteredString = EnteredString.replace(" ","_");
        EnteredString = EnteredString.replace(Original,To + " ");
    } else {
        EnteredString = EnteredString.replace("_"," ");
        EnteredString = EnteredString.replace(To + " ", Original);
    }
}

LoadingProgress.setVisibility(View.GONE);
SetResultText(EnteredString);
ShowResultCardView();

For example, the json response is :

{
    "Response":[
        {"from":"a","to":"bhduh"},{"from":"b","to":"eieja"},{"from":"tes","to":"neesj"}
    ]
}

String.replace() method won't work here, because first it will replace a to bhduh, then b to eieja, BUT here's the problem, it will convert b in bhduh to eieja, which i don't want to.

I want to perfectly convert the letters and "words" in the String according the Json, but that what i'm failing at .

New Code :

if(m_jArry.length() > 0){
    HashMap<String, String> m_li;

    EnteredString = EnteredText.getText().toString();

    Log.i("TestAf_","Before Converting: "  + EnteredString);

    HashMap<String,String> replacements = new HashMap<String,String>();
    for (int i = 0; i < m_jArry.length(); i++) {
        JSONObject jo_inside = m_jArry.getJSONObject(i);

        String Original = jo_inside.getString("from");
        String To = jo_inside.getString("to");

        if(isMethodConvertingIn){

            //EnteredString = EnteredString.replace(" ","_");

            replacements.put(Original,To);
            Log.i("TestAf_","From: " + Original + " - To: " + To + " - Loop: " + i);
            //EnteredString = EnteredString.replace(" ","_");
            //EnteredString = EnteredString.replace(Original,To + " ");

        } else {

            EnteredString = EnteredString.replace("_"," ");
            EnteredString = EnteredString.replace("'" + To + "'", Original);
        }

    }
    Log.i("TestAf_","After Converting: " + replaceTokens(EnteredString,replacements));

    // Replace Logic Here
    // When Finish, Do :
    LoadingProgress.setVisibility(View.GONE);
    SetResultText(replaceTokens(EnteredString,replacements));
    ShowResultCardView();

Output :

10-10 19:51:19.757 12113-12113/? I/TestAf_: Before Converting: ab a ba
10-10 19:51:19.757 12113-12113/? I/TestAf_: From: a - To: bhduh - Loop: 0
10-10 19:51:19.757 12113-12113/? I/TestAf_: From: b - To: eieja - Loop: 1
10-10 19:51:19.757 12113-12113/? I/TestAf_: From: o - To: neesj - Loop: 2
10-10 19:51:19.758 12113-12113/? I/TestAf_: After Converting: ab a ba
like image 345
Jaeger Avatar asked Oct 10 '16 17:10

Jaeger


People also ask

How to replace all occurrences of a string within another string?

With Apache Commons Library, you can simply use Stringutils.replaceEach: public static String replaceEach (String text, String [] searchList, String [] replacementList) Replaces all occurrences of Strings within another String.

How to search and replace multiple words/strings at once?

Example 1. Search and replace multiple words / strings at once To replace multiple words or text in one go, we've created a custom LAMBDA function, named MultiReplace, which can take one of these forms: =LAMBDA (text, old, new, IF (old<>"", MultiReplace (SUBSTITUTE (text, old, new), OFFSET (old, 1, 0), OFFSET (new, 1, 0)), text))

How to replace multiple strings according to the object in JavaScript?

It returns a string, denoting the array values, separated by the defined separator. Example 1: This example uses the RegExp to replace the strings according to the object using the replace () method. JavaScript | Replace multiple strings with multiple other strings.

How do you replace multiple values in a string in Excel?

Multiple find and replace using Substring tools Find and replace multiple values with nested SUBSTITUTE The easiest way to find and replace multiple entries in Excel is by using the SUBSTITUTE function. The formula's logic is very simple: you write a few individual functions to replace an old value with a new one.


2 Answers

You question would be clearer if you gave the expected output for the function.

Assuming it is: ab b test a b >>>> bhduheieja eieja neesjt bhduh eieja

then see the following, the key point in the Javadoc being "This will not repeat"

http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html#replaceEach(java.lang.String,%20java.lang.String[],%20java.lang.String[])

Replaces all occurrences of Strings within another String. A null reference passed to this method is a no-op, or if any "search string" or "string to replace" is null, that replace will be ignored. This will not repeat. For repeating replaces, call the overloaded method.

Example 1

import org.apache.commons.lang3.StringUtils;

public class StringReplacer {

    public static void main(String[] args) {

        String input = "ab b test a b";
        String output = StringUtils.replaceEach(input, new String[] { "a", "b", "tes" },
                new String[] { "bhduh", "eieja", "neesj" });

        System.out.println(input + " >>>> " + output);
    }
}

Example 2

import org.apache.commons.lang3.StringUtils;

public class StringReplacer {

    public static void main(String[] args) {

        String input = "this is a test string with foo";
        String output = StringUtils.replaceEach(input, new String[] { "a", "foo" },
                new String[] { "foo", "bar"});

        System.out.println(input + " >>>> " + output);
    }
}
like image 165
Alan Hay Avatar answered Sep 23 '22 11:09

Alan Hay


Try following:

Solution 1: Traverse the String characters one by one and move the new String to a new StringBuffer or StringBuilder, then call toString() to get the result. This will need you to implement string matching algorithm.

Solution 2 (Using Regex): For this, you must know the domain of your string. For example, it is [a-zA-Z] then other arbitrary characters (not part of domain) can be used for intermediate step. First replace the actual characters with arbitrary one then arbitrary ones with the target. In example below, [!@#] are the arbitrary characters. These can be any random \uxxxx value as well.

String input = "a-b-c";
String output = input.replaceAll("[a]", "!").replaceAll("[b]", "@").replaceAll("[c]", "#");
output = output.replaceAll("[!]", "bcd").replaceAll("[@]", "cde").replaceAll("[#]", "def");
System.out.println("input: " + input);
System.out.println("Expected: bcd-cde-def");
System.out.println("Actual: " + output);
like image 28
Amber Beriwal Avatar answered Sep 23 '22 11:09

Amber Beriwal