gpt4 book ai didi

java - 提取字符串中的字符组

转载 作者:行者123 更新时间:2023-12-02 09:23:29 27 4
gpt4 key购买 nike

我有一个字符串123456789
我还有一堆数字(身份,如果你愿意的话),例如

2 1 1 1 2 2
2 1 1 1 3 1
2 1 1 2 1 2
2 1 1 2 2 1
2 1 1 3 1 1

这个想法是,这些数字指定应该从字符串中提取的数字组(从左到右的顺序,如果重要的话)。因此,像 2 3 2 1 1 这样的数字表示输出前 2 个字符,然后是接下来的 3 个字符,然后是接下来的 2 个字符,然后是接下来的 1 个字符,最后是最后 1 个字符剩余字符。例如,

2 1 1 1 2 2 应输出 12 3 4 5 67 89
2 1 1 1 3 1 应输出 12 3 4 5 678 9
2 1 1 2 1 2 应输出 12 3 4 56 7 89
2 1 1 2 2 1 应输出 12 3 4 56 78 9
2 1 1 3 1 1 应输出 12 3 4 567 8 9

我尝试使用 charAt() 方法,但这似乎不适合我

public static void main(String[] args) {
String mine = "123456789";
System.out.println(mine.charAt(2)+"\t"+mine.charAt(1)+"\t"+
mine.charAt(1)+"\t"+mine.charAt(1)+"\t"+mine.charAt(2)
+"\t"+mine.charAt(2));
}

上面给出了不需要的输出

3   2   2   2   3   3

如何解决这个(对我来说)相当棘手的问题?

最佳答案

这应该可以为您完成工作。

    public static void main(String[] args){
String identities = "2 1 1 1 3 1";

String stringToBreakApart = "123456789";

StringBuilder sb = new StringBuilder();

int currentPosition = 0;

for(String identityString : identities.split(" ")){
int identity = Integer.parseInt(identityString);

sb.append(stringToBreakApart, currentPosition, currentPosition += identity);
sb.append(" ");

}

System.out.println(sb.toString());
}

关于java - 提取字符串中的字符组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58508367/

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