0

I have a large string where I will see a sequence of digits. I have to append a character in front of the number. lets take an example. my string is..

String s= "Microsoft Ventures' start up \"98756\" accelerator wrong launched in apple in \"2012\" has been one of the most \"4241\" prestigious such programs in the country.";

I am looking for a way in Java to add a character in front of each number.so I am expecting the modified string will looks like...

String modified= "Microsoft Ventures' start up \"x98756\" accelerator wrong launched in apple in \"x2012\" has been one of the most \"x4241\" prestigious such programs in the country.";

How do I do that in Java?

2
  • Please properly format the text above (I suppose it is JSON) so it's easier to read, and show us what you already tried. Commented Mar 4, 2015 at 21:49
  • @watery I modified the question. Please look into that. Commented Mar 4, 2015 at 22:49

2 Answers 2

2

The regex to find the numerical part will be "\"[0-9]+\"". The approach I will do is loop through the original string by word, if the word matches the pattern, replace it.

String[] tokens = s.split(" ");
String modified = "";
for (int i = 0 ; i < tokens.length ; i++) {
    // the digits are found
    if (Pattern.matches("\"[0-9]+\"", tokens[i])) {
        tokens[i] = "x" + tokens[i];
    }
    modified = modified + tokens[i] + " ";
}

The code is simply to give you the idea, please optimize it yourself (using StringBuilder to concatenate strings and etc).

Sign up to request clarification or add additional context in comments.

Comments

0

The best way I could see to do this would be to split up the string into various sbustrings and append characters onto it. Something like the following:

 String s="foo \67\ blah \89\"
 String modified=" ";
 String temp =" "; 
 int index=0;
 char c=' ';
 for(int i=0; i<s.length(); ++i) {
   c=s.charAt(i);
   if (Character.isDigit(c)) {
     temp=s.substring(index, i-1);
     modified=modified+temp+'x';
     int j=i;
        while(Character.isDigit(c)) {
           modified+=s[j];
           ++j;
           c=s.charAt(j);
        }
     index=j;
   }
 }

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.