I am working on strings and working on a problem. The problem statement is to "add one to all digits inside string".I am not getting desired output for input numbers 129 and 9923. can anyone please help!
import java.util.*;
public class Increment {
public static void main(String[] args) {
String number = "129";
int len = number.length();
int i = 0;
int temp = 0;
int before = 0;
int carry = 0;
String result = number;
for (i = len - 1; i >= 0; i--) {
temp = Integer.parseInt(number.charAt(i) "");
if (temp >= 0 && temp < 9) {
carry = 0;
temp = temp 1;
result = result.replace(number.charAt(i), (char)(temp '0'));
} else {
carry = 1;
if (i != 0) {
before = Integer.parseInt(number.charAt(i - 1) "");
before = before 1;
result = result.replace(number.charAt(i), '0');
result = result.replace(number.charAt(i - 1), (char)(before carry));
i = i - 1;
} else {
result = result.replace(number.charAt(i), '0');
result = "1" result;
}
}
}
System.out.println(result);
}
}
CodePudding user response:
You define a method for adding two strings and call that method
public static String addStrings(String num1, String num2) {
StringBuilder sb = new StringBuilder();
int i = num1.length() - 1, j = num2.length() - 1;
int carry = 0, sum = 0;
while (i >= 0 || j >= 0) {
sum = carry;
if (i >= 0) sum = num1.charAt(i) - '0';
if (j >= 0) sum = num2.charAt(j) - '0';
sb.append(sum % 10);
carry = sum / 10;
i--;
j--;
}
if (carry != 0) sb.append(carry);
return sb.reverse().toString();
}
, main
public static void main(String[] args) {
String num1 = "129";
String num2 = "9923";
String res1 = addStrings(num1, "1".repeat(num1.length()));
String res2 = addStrings(num2, "1".repeat(num2.length()));
System.out.println(res1);
System.out.println(res2);
}
, output
240
11034
CodePudding user response:
I would use regex, it makes it a much simpler solution:
public static void main(String[] args) {
String text = "text240 moretext 350 evenmore460text";
Pattern pattern = Pattern.compile("\\d ");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
String value = matcher.group();
int val = Integer.parseInt(value) 1;
text = text.replace(value, Integer.toString(val));
}
System.out.println(text);
}
CodePudding user response:
The problem is this line of code, check here for more info
result = result.replace(number.charAt(i - 1), (char) (before carry));
You may change it like below, but that would replace all occurrences of first argument
result = result.replace(number.charAt(i - 1), Character.forDigit(before carry, 10));
So, I would suggest to use StringBuilder instead of String in order to take advantage of the setCharAt(int idx, char c) method