反向打印前n个字符

lrpiutwd  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(304)
import java.util.Scanner;

public class Hello {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        int N = sc.nextInt();
        StringBuilder sb = new StringBuilder(str);
        System.out.print(sb.reverse().toString());
    }
}

输出应为:-

apple
3

ppa

但我得到的是相反的完整字符串

elppa

这样地

oyxsuwqo

oyxsuwqo1#

在代码中根本没有拆分字符串。你需要的是一个 .substring() . 因为你不能在表演完 .substring() 在stringbuilder上,我们只创建自己的反向方法。试试这个:

import java.util.Scanner;

public class Hello {

  public static void main(String[] args) {
    Scanner sc = new Scanner(System. in );
    String str = sc.nextLine();
    int n = Integer.parseInt(sc.nextLine());
    System.out.print(reverse(str.substring(0, n)));
    sc.close();
  }
  public static String reverse(String text) {
    return new StringBuilder(text).reverse().toString();
  }
}

使用严格的stringbuilder方法(根据您的要求),您可以执行以下操作:

import java.util.Scanner;

public class SplitReverse {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        int n = Integer.parseInt(sc.nextLine());
        StringBuilder sb = new StringBuilder(str);
        sb=new StringBuilder(sb.substring(0,n));
        System.out.println(sb.reverse());
        sc.close();
    }
}

不过,我建议您:

import java.util.Scanner;

public class SplitReverse {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        int n = Integer.parseInt(sc.nextLine());
        StringBuilder sb = new StringBuilder(str.substring(0,n));
        System.out.println(sb.reverse());
        sc.close();
    }
}

相关问题