2

I got an issue that I'm not able to solve

I have a paragraph that contains some keywords need to be replaced with new values which are stored in an array

Example:

Paragraph: "My most favorite fruit is [0], but I also like [1] and [3]"

Array: fruits = ["Banana", "Orange", "Apple", "Grape"]

My expectation is: My most favorite fruit is Banana, but I also like Orange and Grape

Could you help me to find a solution for this?

I have tried to convert my sentence into Array of String like this:

["My most favorite fruit is ","[0]",", but I also like ","[1]"," and ","[3]"]

After that, I replace [0] to 0, I got this:

["My most favorite fruit is ","0",", but I also like ","1"," and ","3"]

I tend to replace 0, 1, and 3 in above array into value of fruits[0], fruits[1], fruits[3] then convert that array into a completed string

But I think it's not the best solution, because if I got an input sentence like this: "2[2]" then I will receive the output is AppleApple, whereas the Expectation is 2Apple

1
  • 3
    If your issue "cannot be solved" why are you posting it? Commented Dec 9, 2015 at 12:29

5 Answers 5

3

Java's string formatting has a built-in syntax for this. The general format is:

%[argument_index$][flags][width][.precision]conversion

so you can use e.g. %1$s to mean the first format parameter, %2s the second etc. Note that the indexes are one-based, not zero-based.

e.g.

String[] fruits = {"Banana", "Orange", "Apple", "Grape"};
System.out.format(
    "My most favorite fruit is %1$s, but I also like %2$s and %4$s",
    fruits);
Sign up to request clarification or add additional context in comments.

Comments

2

Use String.replace

String sentence = "My most favorite fruit is [0], but I also like [1] and [3]";
String[] replacements = {"Banana", "Orange", "Apple", "Grape"};
for(int i = 0; i < replacements.length; i++)
    sentence = sentence.replace("[" + i + "]", replacements[i]);

Comments

1

If you are able to change the format of paragraph then you might start from this snippet.

String paragraph = "My most favorite fruit is %s, but I also like %s and %s";
String[] fruits = {"Banana", "Orange", "Apple", "Grape"};
System.out.printf(paragraph, fruits[0], fruits[1], fruits[2]);                 

output

My most favorite fruit is Banana, but I also like Orange and Apple

edit Another solution where don't have to maintain the positional parameters of the fruits could be.

String paragraph = "My most favorite fruit is {0}, but I also like {1} and {3}";
Object[] fruits = {"Banana", "Orange", "Apple", "Grape"};
MessageFormat mf = new MessageFormat(paragraph);
System.out.println(mf.format(fruits));

output

My most favorite fruit is Banana, but I also like Orange and Grape

3 Comments

I want to replace with exact index in source Paragraph, just like [0] should be replaced with fruits[0], and so on ...
@mrzenky Does it mean the placeholders can be in a random order. E.g. John Doe likes [2] and [1], but don't like [3] should result as John Doe likes Apple and Orange, but don't like Grape?
@mrzenky you can use %1$s for that. See Formatter's syntax.
0

You can use the following code (see demo):

ArrayList<String> fruits_arr = new ArrayList<String>(); // Just initializing the array
        fruits_arr.add("Banana");        
        fruits_arr.add("Orange");
        fruits_arr.add("Apple");
        fruits_arr.add("Grape");
    String[] fruits = fruits_arr.toArray(new String[0]);  
    String s = "My most favorite fruit is [0], but I also like [1] and [3]";
    StringBuffer result = new StringBuffer();
    Matcher m = Pattern.compile("\\[(\\d+)\\]").matcher(s); // Initializing Matcher
    while (m.find()) {                          // Iterate over matches
        int num = Integer.parseInt(m.group(1)); // If there is a match, Group 1 has digits
        String replacement = "";
        if (num < fruits.length) {          // If the number is lower than fruit element count
               replacement =fruits[num];   // Get the array element
        } else {
            replacement = m.group();        // Else, use the whole match (e.g. [9])
        }
        m.appendReplacement(result, replacement); // Append this replacement
    }
    m.appendTail(result);
    System.out.println(result.toString());

With \[(\d+)] you match any substring with [+digits+], and capture the digit sequence into Group 1.

2 Comments

like you're using PHP for this ? could I use for java ?
I have re-written the code into Java. Yes, it is something similar to PHP, JS, and other languages where we perform string manipulations inside a callback function in a Replace function.
0

You can use the following:

String str = "My most favorite fruit is [0], but I also like [1] and [3]";
String[] fruits = { "Banana", "Orange", "Apple", "Grape" };

for (int i = 0; i < fruits.length; i++)
{
    str = str.replaceAll("\\[" + i + "\\]", fruits[i]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.