查找字符串数组的索引

时间:2015-05-27 12:03:00

标签: java

我有一个字符串:

String str = "sces123 4096 May 27 16:22 sces123 abc";

我想从字符串中获取sces123 abc。我的代码是:

String[] line = str.split("\\s+");
String name = str.substring(str.indexOf(line[5]));

返回整个字符串。

不知道该怎么做。

任何帮助表示赞赏!

6 个答案:

答案 0 :(得分:1)

您的代码应为

String[] line = str.split("\\s+");
String name = str.substring(str.lastIndexOf(line[5]));

因为str.lastindexOf(line [5])返回0然后子串返回整个String。

答案 1 :(得分:0)

正如Glorfindel所述,sces123评论中line[5]的内容是substring还包含主String str中的第一个indexOf( line[ 5 ]) --> returning 0 str.substring(0) --> returning substring form 0 to last which is the main string 。这就是为什么你得到完整的字符串。

这里真正发生的事情是:

String name = str.substring( str.indexOf( line[ 5 ]+" "+line[6] ) );

如果你只是做了很难编写的东西,那么我不会在这里看到你的目的。

但是你希望你以这种方式得到什么(如果它符合你的目的):

import java.util.Arrays;

public class Delete3 {

    public static void main(String[] args) {

        int num = 246235789;
        int numDigitRequired = 2;

        System.out.println(getLeastNum(num, numDigitRequired));
    }

    static int getLeastNum(int num, int numDigitRequired) {

        char[] a = (num + "").toCharArray();

        Arrays.sort(a);

        StringBuffer s = new StringBuffer();

        for (int i = 0; i < numDigitRequired; i++)
            s.append(Character.getNumericValue(a[i]));

        return Integer.parseInt(s.toString());
    }
}

答案 2 :(得分:0)

在您的情况下,您只需要更改str.indexOf -> str.lastIndexOf

答案 3 :(得分:0)

这是一个简单的解决方案:

String str = "sces123 4096 May 27 16:22 sces123 abc";
//split spaces
String[] line = str.split(" ");
//get 2 last columns
String name = (line[5] + " " + line[6]);
System.out.println(name);

答案 4 :(得分:0)

您可以使用Matcher查找第5场比赛的结尾:

String str = "sces123 4096 May 27 16:22 sces123 abc";
Pattern p = Pattern.compile("\\s+");
Matcher m = p.matcher(str);

for (int i = 0; i < 5; i++) {
    m.find();
}

String name = str.substring(m.end());

在我看来,这比使用lastIndexOf更好地连接索引5和6处的元素更好,原因如下:

  • 不需要line[5]成为该字符串的最后一次出现。

    使用lastIndexOf不适用于输入

    "sces123 4096 May 27 16:22 sces123 sces123"
    
  • 它也适用于arbirtrary长度的分隔符字符串。

    使用line[ 5 ]+" "+line[6]不适用于输入

    "sces123 4096 May 27 16:22 sces123             abc"
    
  • split之后的数字元素不需要为7。

    使用line[ 5 ]+" "+line[6]不适用于输入

    "sces123 4096 May 27 16:22 sces123 abc def"
    

答案 5 :(得分:0)

试试这个:

        String str = "sces123 4096 May 27 16:22 sces123 abc";
        String[] line = str.split("\\s+");

        System.out.println(str.substring(str.lastIndexOf(line[5])));
相关问题