Ali Haider
Ali Haider

Reputation: 1

Find index of a string array

I have a string :

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

I want to get sces123 abc from the string. My code is :

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

It returns the whole string.

Dont know how to do.

any help appreciated!

Upvotes: 0

Views: 101

Answers (6)

fabian
fabian

Reputation: 82521

You could use a Matcher to find the end of the 5th match:

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());

In my opinion this is better than using lastIndexOf on to concatenating elements at indices 5 and 6, for the following reasons:

  • It does not require line[5] to be the last occurence of that string.

    Using lastIndexOf doesn't work for input

    "sces123 4096 May 27 16:22 sces123 sces123"
    
  • It also works for seperator strings of arbirtrary length.

    Using line[ 5 ]+" "+line[6] doesn't work for input

    "sces123 4096 May 27 16:22 sces123             abc"
    
  • It does not require the number elements after the split to be 7.

    Using line[ 5 ]+" "+line[6] doesn't work for input

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

Upvotes: 0

Sonu Gupta
Sonu Gupta

Reputation: 367

Try This:

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

        System.out.println(str.substring(str.lastIndexOf(line[5])));

Upvotes: 0

StephaneM
StephaneM

Reputation: 4899

Your code should be

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

because str.lastindexOf(line[5]) returns 0 and then the substring returns the whole String.

Upvotes: 1

Saif
Saif

Reputation: 7052

As Glorfindel said in the comment sces123 which is the content of if line[5] also contain as the first substring in the main String str. That why you are getting the full string.

Whats really happening here is:

indexOf( line[ 5 ]) --> returning 0
str.substring(0) -->  returning substring form 0 to last which is the main string

If you are only doing the hard codded things then i don't see the purpose of you here.

But What you want you get in this way (if it serve your purpose ) :

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

Upvotes: 0

gtzinos
gtzinos

Reputation: 1197

This is one easy solution :

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);

Upvotes: 0

Aliaksei Yatsau
Aliaksei Yatsau

Reputation: 749

In your case you just need to change str.indexOf -> str.lastIndexOf.

Upvotes: 0

Related Questions