user2839999
user2839999

Reputation: 101

replace part of a string in java

I'm trying to write a function which takes in a string such as String code = "<div> style="width: 3%" </div>"

I would like to replace the 3% to another number (can be more than 2 digits) so 400% etc.

I'm currently getting the charAt(21) but this is only the index of 3, so if I had 20% in that place then my code would not work.

Is there another way to replace the place where the % is stored. (also doing this by not knowing what number the current % is)

Upvotes: 0

Views: 1087

Answers (5)

mattinbits
mattinbits

Reputation: 10428

You can do this using a regular expression, for example:

String code = "<div> style=\"width: 3%\" </div>"
String replaced = code.replaceFirst("width: \\d+", "width: 400")

To extract the value in the existing string:

Pattern pattern =  Pattern.compile("width: (\\d+?)%");
Matcher matcher = pattern.matcher(code);
matcher.find()
matcher.group(1)//Gives 3

Upvotes: 1

Ali Yeşilkanat
Ali Yeşilkanat

Reputation: 607

You can use HTML parser such as Jsoup.

Upvotes: 0

Eric Taix
Eric Taix

Reputation: 908

Use String#replaceFirst or String#replaceAll method: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

code = code.replaceFirst("width: ?(.*)%", "width: 400%");

Of course adapt the regex to your requirement

Upvotes: 0

Francisco Romero
Francisco Romero

Reputation: 13199

If your String it's:

String code = "<div> style="width: 3%" </div>"

You can find the position in which the % it's stored, like this:

int position = code.indexOf("%");

And suppossing that you have your number stored in a String:

String number = "2";

Note: It doesn't matter if it is 2 or 22 or 222.

You can get the total String with substring function:

String totalString = code.substring(0,position - 1) + number + code.substring(position+1, code.length());

And now you can print it normally:

System.out.println(totalString);

I expect it will works for you!

Upvotes: 0

Maroun
Maroun

Reputation: 95958

The best approach would be using HTML parser. But if your string will always be simple, you can use replaceAll which takes a regex:

String code = "<div> style=\"width: 3%\" </div>";
String res = code.replaceAll(yourRegex, replacement);

I will leave the full solution for you, but will give you few hints:

  • Regex tutorial
  • String#replaceAll
  • \d+ will match digits, so width:\s+\d+ will match "width" followed by space(s) and then digit(s)
  • Use parenthesis to group the caught result from the regex, for example width:\s+(\d+) will catch the result of the digits (group)

Upvotes: 1

Related Questions