如何在Java中按位置拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4023146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to split a string by position in Java
提问by Roger22
I did not find anywhere an answer.. If i have: String s = "How are you"
?
How can i split this into two strings, so first string containing from 0..s.length()/2
and the 2nd string from s.length()/2+1..s.length()
?
我没有找到任何答案.. 如果我有:String s = "How are you"
?我怎样才能把它分成两个字符串,所以第一个字符串包含 from0..s.length()/2
和第二个字符串 from s.length()/2+1..s.length()
?
Thanks!
谢谢!
回答by Alois Cochard
You can use 'substring(start, end)', but of course check if string isn't null before:
您可以使用 'substring(start, end)',但当然之前检查字符串是否为空:
String first = s.substring(0, s.length() / 2);
String second = s.substring(s.length() / 2);
And are you expecting string with odd length ? in this case you must add logic to handle this case correctly.
并且您期待具有奇数长度的字符串吗?在这种情况下,您必须添加逻辑以正确处理这种情况。
回答by Buhake Sindi
Use String.substring(int), and String.substring(int, int)method.
使用String.substring(int)和String.substring(int, int)方法。
int cutPos = s.length()/2;
String s1 = s.substring(0, cutPos);
String s2 = s.substring(cutPos, s.length()); //which is essentially the same as
//String s2 = s.substring(cutPos);
回答by aioobe
This should do:
这应该做:
String s = "How are you?";
String first = s.substring(0, s.length() / 2); // gives "How ar"
String second = s.substring(s.length() / 2); // gives "e you?"
String.substring(int i)
with one argument returns the substring beginning at positioni
String.substring(int i, int j)
with two arguments returns the substring beginning ati
and ending atj-1
.
String.substring(int i)
带一个参数返回从位置开始的子字符串i
String.substring(int i, int j)
带有两个参数返回从 开始到i
结束的子字符串j-1
。
(Note that if the length of the string is odd, second
will have one more character than first
due to the rounding in the integer division.)
(请注意,如果字符串的长度是奇数,second
则会比first
整数除法中的舍入多一个字符。)
回答by BigMac66
String s0 = "How are you?";
String s1 = s0.subString(0, s0.length() / 2);
String s2 = s0.subString(s0.length() / 2);
So long as s0 is not null.
只要 s0 不为空。
EDIT
编辑
This will work for odd length strings as you are not adding 1 to either index. Surprisingly it even works on a zero length string "".
这将适用于奇数长度的字符串,因为您没有向任一索引添加 1。令人惊讶的是,它甚至适用于零长度字符串“”。
回答by Sean Patrick Floyd
Here's a method that splits a string into nitems by length. (If the string length can not exactly be divided by n, the last item will be shorter.)
这是一种按长度将字符串拆分为n 个项目的方法。(如果字符串长度不能被n整除,最后一项会更短。)
public static String[] splitInEqualParts(final String s, final int n){
if(s == null){
return null;
}
final int strlen = s.length();
if(strlen < n){
// this could be handled differently
throw new IllegalArgumentException("String too short");
}
final String[] arr = new String[n];
final int tokensize = strlen / n + (strlen % n == 0 ? 0 : 1);
for(int i = 0; i < n; i++){
arr[i] =
s.substring(i * tokensize,
Math.min((i + 1) * tokensize, strlen));
}
return arr;
}
Test code:
测试代码:
/**
* Didn't use Arrays.toString() because I wanted to have quotes.
*/
private static void printArray(final String[] arr){
System.out.print("[");
boolean first = true;
for(final String item : arr){
if(first) first = false;
else System.out.print(", ");
System.out.print("'" + item + "'");
}
System.out.println("]");
}
public static void main(final String[] args){
printArray(splitInEqualParts("Hound dog", 2));
printArray(splitInEqualParts("Love me tender", 3));
printArray(splitInEqualParts("Jailhouse Rock", 4));
}
Output:
输出:
['Hound', ' dog']
['Love ', 'me te', 'nder']
['Jail', 'hous', 'e Ro', 'ck']
['Hound', 'dog']
['Love', 'me te', 'nder']
['Jail', 'hous', 'e Ro', 'ck']
回答by Stephen C
I did not find anywhere an answer.
我没有找到任何答案。
The first place you should always look is at the javadocs for the class in question: in this case java.lang.String
. The javadocs
您应该始终查看的第一个位置是相关类的 javadoc:在本例中为java.lang.String
. javadocs
- can be browsed online on the Oracle website (e.g. at http://download.oracle.com/javase/6/docs/api/),
- are included in any Sun/Oracle Java SDK distribution,
- are probably viewable in your Java IDE, and
- and be found using a Google search.
- 可以在 Oracle 网站(例如http://download.oracle.com/javase/6/docs/api/)上在线浏览,
- 包含在任何 Sun/Oracle Java SDK 发行版中,
- 可能在您的 Java IDE 中可见,并且
- 并使用 Google 搜索找到。
回答by JyotiKumarPoddar
public int solution(final String S, final int K) {
int splitCount = -1;
final int count = (int) Stream.of(S.split(" ")).filter(v -> v.length() > K).count();
if (count > 0) {
return splitCount;
}
final List<String> words = Stream.of(S.split(" ")).collect(Collectors.toList());
final List<String> subStrings = new ArrayList<>();
int counter = 0;
for (final String word : words) {
final StringJoiner sj = new StringJoiner(" ");
if (subStrings.size() > 0) {
final String oldString = subStrings.get(counter);
if (oldString.length() + word.length() <= K - 1) {
subStrings.set(counter, sj.add(oldString).add(word).toString());
} else {
counter++;
subStrings.add(counter, sj.add(word).toString());
}
} else {
subStrings.add(sj.add(word).toString());
}
}
subStrings.forEach(
v -> {
System.out.printf("[%s] and length %d\n", v, v.length());
}
);
splitCount = subStrings.size();
return splitCount;
}
public static void main(final String[] args) {
public static void main(final String[] args) {
final MessageSolution messageSolution = new MessageSolution();
final String message = "SMSas5 ABC DECF HIJK1566 SMS POP SUV XMXS MSMS";
final int maxSize = 11;
System.out.println(messageSolution.solution(message, maxSize));
}