0

I have trouble splitting a name by a space, and I can't seem to figure out why. Could someone please provide me with a solution?

My code is like this:

 public void getPlayerNames(int id){
    try {
        Document root = Jsoup.connect("http://www.altomfotball.no/element.do?cmd=team&teamId=" + id).get();
        Element table = root.getElementById("sd_players_table");
        Elements names = table.getElementsByTag("a");

        for(Element name : names){
            getPlayers().add(new Player(name.text()));
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

which returns the name of football players as a string. The names are retrieved such as Mario Balotelli, Steven Gerrard, and so on, and I assumed I could use string.split(" "); to get me the first and last names, but whenever I try to access the second space of the string array it gives me an index out of bounds exception. Here is the code trying to fetch me the first name

/**
 * Method to get the first name of a player
 */
public static String getFirstName(String name){
    String[] nameArray = name.split(" ");
    return nameArray[0];
}

Thanks for answers!

Sindre M

EDIT ###### So I got it to work, but thanks for the effort. The problem was that even though I could not see it in a simple sysout statement, the names actually contained a "&nbsp"; character, so I solved it by running a replaceAll("&nbsp ;" , " ") on the names for a better formatting.

  • Can you show a runable example? – Jens Feb 17 '15 at 06:55
  • try to print the name before splitting as it might not have space in it. – SMA Feb 17 '15 at 06:55
  • did you check with logging what the name is? If there is no space in the `String name` there is no `nameArray[1]` (second part what gives the array out of bound exception) – chillworld Feb 17 '15 at 06:56

5 Answers5

0

If you're trying to write a screen-scraper you need to be more defensive in your code... Definitely test the length of the array first and log any unexpected inputs so you can incorporate them later...

public static String getFirstName(String name) {
    String[] nameArray = name.split(" ");
    if (nameArray.length >= 1) {  // <== check length before you access nameArray[0]  
        return nameArray[0];   
    } else {
        // log error
    }
    return null;
}

Additionally java.util.Optional in Java 8 provides a great alternative to returning null...

public static Optional<String> getFirstName(String name) {
    String[] nameArray = name.split(" ");
    if (nameArray.length >= 1) {
        return Optional.of(nameArray[0]);
    } else {
        // log error
    }
    return Optional.empty();
}
Adam
  • 35,919
  • 9
  • 100
  • 137
  • actually nameArray[0] will **always** be there(if no nullpointer is thrown), even if there was no split done. It's nameArray[1] who gave the index out of bounds exception. – chillworld Feb 17 '15 at 07:43
0

You might be getting   in the actual string as you are retrieving from html page. try to debug and check.

0
package com.appkart.examples;

public class SplitProgram {

    public void firstNameArray(String nameString) {
        String strArr[] = nameString.split(",");

        for (String name : strArr) {
            String playerName = name.trim();
            String firstName = playerName.substring(0, playerName.indexOf(" "));
            System.out.println(firstName);
        }
    }

    public static void main(String[] args) {
        String nameString = "Mario Balotelli, Steven Gerrard";
        SplitProgram program = new SplitProgram();
        program.firstNameArray(nameString);
    }
}
Arun Kumar
  • 2,874
  • 1
  • 18
  • 15
0

I think that the correct answer should be:

   String[] nameArray = name.split("\\s+");

But to be honest, there are couple of answers at stackoverflow. Eg.

How to split a String by space

How do I split a string with any whitespace chars as delimiters?

Community
  • 1
  • 1
Kamil Kubacki
  • 867
  • 6
  • 8
0

First try to replace white space as

string.replace(" ","");

then try to split with [,] as

String strAr[] = string.split(",");
The N..
  • 70
  • 1
  • 5
  • what happens if the string already contains character ',' . Ex : "jhone,j wick" jhone,j should be the first name.? by the way your first line should be string.replace(" ",","); ',' missing – prasadmadanayake Feb 17 '15 at 08:11
  • You are write, if name contains [,] there will be a problem but i don't think it will happen. Bcz the sample shared in the questions such as Mario Balotelli, Steven Gerrard, and so on. Assuming there will not be any such string. – The N.. Feb 17 '15 at 08:17