【问题标题】:How do I reverse the order of only the digits in a string?如何反转字符串中仅数字的顺序?
【发布时间】:2015-05-31 17:22:21
【问题描述】:

在Java中给定一个字符串,如何获得一个所有相邻数字序列都反转的新字符串?

我的代码:

import static java.lang.System.*;

public class P2
{
    public static void main(String[] args)
    {
        if(args.length < 1)
        {
            err.printf("Usage: java -ea P2 String [...]\n");
            exit(1);
        }

        String[] norm = new String[args.length];
        for(int i = 0; i<norm.length;i++)
        {
            norm[i] = args[i];
        }
    }

    public String invertDigits(String[] norm)
    {   

    }
}

作为一个例子,这就是它应该做的:

输入:1234 abc9876cba a123 312asd a12b34c56d

1234 -> 4321

abc9876cba -> abc6789cba

a123 -> a321

312asd -> 213asd

a12b34c56d -> a21b43c65d

【问题讨论】:

  • 您应该给出一个示例字符串以及您期望从中得到什么结果以帮助我们理解。另外,到目前为止,您尝试过什么?
  • 有什么例子吗?你试过什么了?您尝试过任何代码吗?
  • 我编辑了问题
  • 命令行选项应该做什么?
  • 我如何输入字符串并不重要,程序应该获取字符串并反转数字的顺序,直到找到一个空格,然后它应该从那时起做同样的事情直到它找到另一个空格,忽略任何不是数字的东西

标签: java string reverse digits


【解决方案1】:

尽管这个问题被严重否决,但现在提出的问题似乎很清楚。我选择在递归函数中使用regular expression match 来解决它。

private static String reverseDigits(String s) {
    // the pattern will match a sequence of 1 or more digits
    Matcher matcher = Pattern.compile("\\d+").matcher(s);
    // fetch the position of the next sequence of digits
    if (!matcher.find()) {
        return s; // no more digits
    }
    // keep everything before the number
    String pre = s.substring(0, matcher.start());
    // take the number and reverse it
    String number = matcher.group();
    number = new StringBuilder(number).reverse().toString();

    // continue with the rest of the string, then concat!
    return pre + number + reverseDigits(s.substring(matcher.end()));
}

这是迭代方法。

private static String reverseDigits(String s) {
    //if (s.isEmpty()) return s;
    String res = "";
    int base = 0;
    Matcher matcher = Pattern.compile("\\d+").matcher(s);
    while (!matcher.hitEnd()) {
        if (!matcher.find()) {
            return res + s.substring(base);
        }
        String pre = s.substring(base, matcher.start());
        base = matcher.end();
        String number = matcher.group();
        number = new StringBuilder(number).reverse().toString();
        res += pre + number;
    }
    return res;
}

【讨论】:

    【解决方案2】:
        String str = "1234";
    
        //indexes
        int i = 0, j = str.length()-1;
    
        // find digits (if any)
        while (!Character.isDigit(str.charAt(i)) && i < str.length()) {
            i++;
        }
        while (!Character.isDigit(str.charAt(j)) && j >= 0) {
            j--;
        }
    
        // while we havent searched all the digits
        while (i < j) {
            // switch digits
            str = str.substring(0, i) + str.charAt(j) + str.substring(i + 1, j) + str.charAt(i) + str.substring(j + 1);
            i++;
            j--;
            // find the next digits
            while (!Character.isDigit(str.charAt(i)) && i < str.length()) {
                i++;
            }
            while (!Character.isDigit(str.charAt(j)) && j >= 0) {
                j--;
            }
        }
        System.out.println(str);
    

    【讨论】:

      【解决方案3】:

      另一种不使用正则表达式类的动态方法:

      public static String reverseOnlyNumbers(String s) {
          StringBuilder digits = new StringBuilder();
          StringBuilder result = new StringBuilder();
      
          boolean start = false;
      
          for (int i = 0; i < s.length(); i++) {
              Character c = s.charAt(i);
      
              if (Character.isDigit(c)) {
                  start = true;
                  digits.append(c);
              }else {
                  start = false;
                  if (digits.length() > 0) {
                      result.append(digits.reverse().toString());
                      digits = new StringBuilder();
                  }
                  result.append(c);
              }
          }
      
          return start ? result.append(digits.reverse()).toString() : result.toString();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-01
        • 2010-11-03
        • 2011-11-07
        相关资源
        最近更新 更多