有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我需要从输入中提取前N个字符

我刚刚开始学习Java。我需要从输入中提取前N个字符。输入包括输入字符串开头的字符数,然后是字符数。输出包括开头的数字

例如,如果用户输入“3stars”,输出将是“3st”,或者输入“7Appendments”,输出将是“7append”

尝试了以下方法:

  Scanner input = new Scanner(System.in);
      System.out.print("Please enter a uncoded string: ");
      String first = input.nextLine();
      input.close();

      if (first.charAt(0) == 'u') {
          first = first.toUpperCase();
      } else if (first.charAt(0) == 'l') {
          first = first.toLowerCase();
      } else if (first.charAt(0) == 'e') {
            String str = "";
            for (int i = 0; i < first.length(); i = i + 2) {
                str += first.charAt(i);
            }
            first = str;
        } else if (first.charAt(0) == 'o') {
            String str = "";
            for (int i = 1; i < first.length(); i = i + 2) {
                str += first.charAt(i);
            }
            first = str;
        } else if (first.charAt(0) == 1++) {
            String str = "";
            for (int i = 1++ ; i < first.length(i); i = i charAt(i)) {
                str += first.charAt(i);
            }
            first = str;

任何帮助都会很好


共 (2) 个答案

  1. # 1 楼答案

    我希望这有助于:

    int num = Character.getNumericValue(first.charAt(0));
    
    String str = "";
    for(int i = 0;i < num;i++){
       str += first.charAt(i);
    }
    System.out.println(str);
    
  2. # 2 楼答案

    这也适用于11abcdefghijklmnopqrstuvwxyz等数字大于9的输入

    public static void main(String[] args) {
        String input = "7appendices";
        // match numbers
        Pattern p = Pattern.compile("^([0-9]+)");
        // by default at least the integer has one digit
        int digits = 1;
        int length = 0;
        // while the beginning of the input match an integer
        while (p.matcher(input.substring(0, digits)).matches()) {
            // set length as the integer at the beginning
            length = Integer.parseInt(input.substring(0, digits));
            // increase the amount of digits from the integer in the input
            digits++;
        }
        System.out.println(input.substring(0, length));
    }
    

    你只需要像这样用scanner替换输入

     String input = new Scanner(System.in).next();