获取除字符串中的最后一个单词之外的每个单词的最简单方法
除了字符串中的最后一个单词之外,在字符串中获取每个单词的最简单方法是什么? 到目前为止,我一直在使用以下代码来得到最后一句话:
String listOfWords = "This is a sentence"; String[] b = listOfWords.split("\\s+"); String lastWord = b[b.length - 1];
然后通过使用remove方法从字符串中删除最后一个单词来获取字符串的其余部分。
我不想使用remove方法,有没有类似于上面的代码集来获得一个不同的单词串而没有最后一个单词和最后一个空格?
喜欢这个:
String test = "This is a test"; String firstWords = test.substring(0, test.lastIndexOf(" ")); String lastWord = test.substring(test.lastIndexOf(" ") + 1);
你可以得到lastIndexOf空格并使用子串,如下所示:
String listOfWords = "This is a sentence"; int index= listOfWords.lastIndexOf(" "); System.out.println(listOfWords.substring(0, index)); System.out.println(listOfWords.substring(index+1));
输出:
This is a sentence
尝试将String.lastIndexOf
方法与String.substring
结合使用。
String listOfWords = "This is a sentence"; String allButLast = listOfWords.substring(0, listOfWords.lastIndexOf(" "));
我在你的代码中添加了一行,这里没有删除
String listOfWords = "This is a sentence"; String[] b = listOfWords.split("\\s+"); String lastWord = b[b.length - 1]; String rest = listOfWords.substring(0,listOfWords.indexOf(lastWord)).trim(); // Added System.out.println(rest);
这将满足您的需求:
.split("\\s+[^\\s]+$|\\s+")
例如:
"This is a sentence".split("\\s+[^\\s]+$|\\s+");
返回:
[This, is, a]
public class StringArray {
/** * @param args the command line arguments */ public static void main(String[] args) { String sentense="this is a sentence"; int index=sentense.lastIndexOf(" "); System.out.println(sentense.substring(0,index)); }
}