如何在java中的空格之前删除文本?

时间:2015-06-26 12:40:07

标签: java string

String str = "hello world";
int spacePos = str.indexOf(" ");
if (spacePos > 0) {
    String youString = str.substring(0, spacePos - 1);
    System.out.println(youString);
}

我想要" world" 。我如何得到这个结果?

3 个答案:

答案 0 :(得分:6)

使用substring(startIndex)形式的substring方法。 找到空格的索引(''),将结果+ 1 传递给substring方法,它将输出从该位置开始到结尾的字符串。如下:

String str = "hello world";
String youString = str.substring(str.indexOf(' ') + 1);
System.out.println(youString);

答案 1 :(得分:3)

您应首先检查您的字符串是否包含空格,这样您也不必检查index > 0

String str = "hello world";
if (!str.contains(" ")){
    //Stop, handle this situation, throw an exception, whatever you want 
    //I'm just returning an empty string for simplicity now.
    return "";
}

int spacePos = str.indexOf(" ");
String suffix = str.substring(spacePos + 1, str.length()); //Gets the 'world' part

答案 2 :(得分:0)

有一种方法,尽管还有很多其他方法,你可以使用string.split(\ s),我相信它会在找到指定字符的任何地方(在本例中为空格)将字符串拆分,并将子字符串存储在数组中。然后你可以抓住你想要的索引,在这种情况下是第二个元素so array [1]