gpt4 book ai didi

java - 将文本字符串中的字符移动指定数量的位置

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:22:31 25 4
gpt4 key购买 nike

我是编程新手,我正在尝试编写一个程序,将文本字符串中的字符移动指定数量的位置。

程序必须包含一个方法,其输入将是文本字符串(String 类型)和位置数(int 类型)。输出将是一个字符移位的字符串。

例如移动4个位置:

rabbit eats a carrotit eats a carrotrabb

Now I have this partial code. I can erase first characters but I don't know how to put them to the end of this text. How can i make it?

public static void main(String[] args) {
System.out.println("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.println("enter number of positions= ");
int b = cti.nextInt();
char firstLetter = a.charAt(0);
b--;
a = a.substring(b);
String m = a + firstLetter ;
System.out.println("now it is "+ m);
}

最佳答案

如果你使用正则表达式,它只是一行:

return str.replaceAll("^(.{" + n + "})(.*)", "$2$1");

关于java - 将文本字符串中的字符移动指定数量的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27214783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com