我有一个字符串,想要在一些字符之后将其拆分......
示例代码:
//This is what I have:
String text = "12345678";
List<String> tmpListFirst = new LinkedList<>();
List<String> tmpListSecond = new LinkedList<>();
int splitAfter = 3; //split after the second character (this value is variable)
//The result should look like this:
tmpListFirst.get(0) //== 678
tmpListFirst.get(0) //== 12345
答案 0 :(得分:3)
String text = "12345678";
int splitAfter = 3;
List<String> tmpListFirst = new LinkedList<>();
List<String> tmpListSecond = new LinkedList<>();
tmpListFirst.add(text.substring(0, splitAfter));
tmpListSecond.add(text.substring(splitAfter));
如果您想要存储在列表中的值,那就是
。否则它们只能通过执行String s1 = text.substring(0, splitAfter);
和/而存储在字符串中
String s2 = text.substring(splitAfter);
答案 1 :(得分:1)
String text = "12345678";
text = text.substring(0, 1) //will print 1
text = text.substring(3, text.length()) //will print 45678
text = text.substring(3) //will also print 45678
应该是您正在寻找的。比在n个字符
之后使用String.split()方法容易得多答案 2 :(得分:1)
试试这段代码。这将为您提供完全理想的结果:
String text = "12345678";
List<String> tmpListFirst = new LinkedList<>();
List<String> tmpListSecond = new LinkedList<>();
int splitAfter = 5; //split after the second character (this value is variable)
//The result should look like this:
tmpListFirst.add(text.substring(splitAfter));//678
tmpListSecond.add(text.substring(0, splitAfter)); //== 12345
System.out.println(tmpListFirst.get(0));
System.out.println(tmpListSecond.get(0));
如果您不需要使用List或LinkedList,那么程序将非常简单,如: -
String text = "12345678";
int splitAfter = 5; //split after the second character (this value is variable)
System.out.println(text.substring(splitAfter)); //678
System.out.println(text.substring(0, splitAfter)); //12345
答案 3 :(得分:0)
如果我理解正确,你想要像
那样做String text = "12345678";
System.out.println(text.substring(0, 5));
System.out.println(text.substring(5));
//-----------output-------------
12345
678