簡體   English   中英

對字符串中的所有數字加 1

[英]add 1 to all digits in string

我正在處理字符串並解決問題。 問題陳述是“將字符串內的所有數字加一”。我沒有得到輸入數字 129 和 9923 的所需輸出。任何人都可以幫忙!

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);
  }
}

您定義一個添加兩個字符串的方法並調用該方法

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);
}

,輸出

240
11034

我會使用正則表達式,它使它成為一個更簡單的解決方案:

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);
}

問題是這行代碼,查看這里了解更多信息

result = result.replace(number.charAt(i - 1), (char) (before + carry));

您可以像下面這樣更改它,但這將替換所有出現的第一個參數,正如@user16320675 指出的那樣

result = result.replace(number.charAt(i - 1), Character.forDigit(before + carry, 10));

因此,我建議使用 StringBuilder 而不是 String 以利用 setCharAt(int idx, char c) 方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM