Ali
Ali

Reputation: 13

Splitting string on first character makes first element null. How to get around this?

So let's say I have this string:

+-5

I'm splitting at the + sign into an array. My first element is null and my second element is -5. How can I get around this and make the first element just -5?

Edit: Here's some of my code:

Scanner sc = new Scanner(System.in);

System.out.print("Enter polynomial function: ");

String function = sc.nextLine();
function = function.replaceAll("-", "+-").replaceAll(" ", "");

String[] terms = function.split("\\+");

I'm trying to get the coefficients of the polynomial by first replacing all - with +-

-5x^2 + 3x -2
+-5x^2 +3x +-2
Now it should split wherever there is a + sign.
First element is null, second element is -5x^2, third element 3x and fourth is -2

Upvotes: 1

Views: 2309

Answers (3)

rolfl
rolfl

Reputation: 17707

One relatively simple way to solve the problem is to create your own function that checks the first character of the String manually:

public static String[] splitPlus(String input) {
    String toSplit = (!input.isEmpty() && input.charAt(0) == '+') ? input.substring(1) : input;
    return toSplit.split("\\+");
}

Upvotes: 1

qingbo
qingbo

Reputation: 2160

You may want to try commons lang library's StringUtils:

String[] terms = StringUtils.split(function, '+');
for (String term : terms) {
    System.out.println(term);
}

Output:

-5x^2
3x
-2

It also strips the spaces.

Upvotes: 0

nobalG
nobalG

Reputation: 4620

split() method perform the splitting in a special way.It creates the array of substrings of the patterns finishing with the character specified in the brackets of split,so in your case ,there is nothing in front of '+' hence it returns empty string at the zero index of the array returned.To perform your desired operation,

  • Either you can have a check for empty string there
  • Or start from the first index of the array returned

See this Java String.split() sometimes giving blank strings too

Upvotes: 0

Related Questions