I wanted to add two numbers to the value in center of the square bracket.
Eg: I have String [00:25.30] it needs to be converted to [00:27.30]
How can i do this in Java?
4 Answers
I would forgoe the part about the regular expression and work with the bare values here:
String[] numbers = string.substring(1, 9).replace(".", ":").split(":");
int value = Integer.parseInt(numbers[1]);
String result = "[" + numbers[0] + ":" + (value + 2) + "." + numbers[2] + "]";
That way you can later change other values as well.
2 Comments
David Koelle
The second separator in the original post is a period, not a colon, so the split() won't work against the input.
TreffnonX
Correct. Changed the suggestion accordingly.
If you always know that your two numbers in the center of the square brackets are going to be bounded by the same characters, and those characters will not appear elsewhere in the string, I would recommend using a simple substring instead of a regex.
For example:
public class AddToString {
public static final char SEPARATOR_1 = ':';
public static final char SEPARATOR_2 = '.';
public static String getAddedString(String input, int add) {
int pos1 = input.indexOf(SEPARATOR_1);
int pos2 = input.indexOf(SEPARATOR_2);
StringBuilder builder = new StringBuilder();
builder.append(input.substring(0, pos1+1));
builder.append(Integer.parseInt(input.substring(pos1+1, pos2)) + add);
builder.append(input.substring(pos2, input.length()));
return builder.toString();
}
public static void main(String[] args) {
System.out.println(getAddedString("[00:25.30]", 2));
}
}
Comments
This has no null checks or formatting checks, but it will get you started.
public String addValue(String string, int valueToAdd) {
int newValue = Integer.parseInt(string.substring(string.indexOf(":") + 1, string.indexOf(".")));
String stringToReturn = string.replaceAll(":*\\.", ":" + newValue + ".");
}
Comments
I would go for something like this:
String s = "[00:25.30]";
StringTokenizer st = new StringTokenizer(s,":");
StringBuilder output = new StringBuilder();
output.append(st.nextToken());
st = new StringTokenizer(st.nextToken(),".");
output.append(':').append(String.valueOf(Integer.valueOf(st.nextToken()) + 2));
output.append(".").append(st.nextToken());
System.out.println(output);
s/(\[\d+:)(\d+)(:\d+\])/$1.($2+2).$3/es/and/matches the three parts '[00:', '25', and ':30]', respectively. Second part between/and/ereplaces the matched part of the string with the value of the first group ($1), concatenated (.) with value of the second group plus 2 ($2+2), concatenated with the value of the third group ($3).