在java中的特定位置拆分字符串 [英] Splitting a string at a particular position in java
问题描述
假设您有一个 "word1 word2 word3 word4"
形式的字符串.拆分它的最简单方法是什么,split[0] = "word1 word2"
和 split[1] = "word3 word4"
?
Assume you have a string of the form "word1 word2 word3 word4"
. What is the simplest way to split it such that split[0] = "word1 word2"
and split[1] = "word3 word4"
?
澄清
我想拆分,而不是 split[0] = "word1",我有前 2 个词(我同意它不清楚)和 split[1] 中的所有其他词,即在第二个空格
I want to split such that instead of having split[0] = "word1", I have the first 2 words (I agree it was not clear) and all the other words in split[1], ie on the second space
推荐答案
我会使用 String.substring(beginIndex, endIndex);和 String.substring(beginIndex);
I would use the String.substring(beginIndex, endIndex); and String.substring(beginIndex);
String a = "word1 word2 word3 word4";
int first = a.indexOf(" ");
int second = a.indexOf(" ", first + 1);
String b = a.substring(0,second);
String c = b.subString(second); // Only startindex, cuts at the end of the string
这将导致 a = "word1 word2" 和 b = "word3 word4"
This would result in a = "word1 word2" and b = "word3 word4"
这篇关于在java中的特定位置拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!