0

Can you split a string in Java without storing what has been split into variables? (Assignment requirement :()

I have tried things which worked on other programming languages however nothing I try seems to work:

(Attempting to see if the second item in a space delimited string (x) is +)

if ((x.split.(" ")).(1) = "+") {
            // Do something
        }

if ((x.split.(1).(" ")) = "+") {
            // Do something
        }
Thahleel al-Aleem
  • 711
  • 2
  • 10
  • 20
  • 1
    Can you quote, word for word, the requirement? `String#split(..)` returns an value of type `String[]`. – Sotirios Delimanolis Nov 10 '14 at 21:24
  • You must NOT declare any variables or make any methods which are not in this class. You may use classes from the Java library but the outputs must be stored in existing variables. The only variable available to use is a parameter string called x and a double called x – Thahleel al-Aleem Nov 10 '14 at 21:25
  • 1
    also x.split.(" ")).(1) = "+") is purely wrong wrong wrong! Crying out for syntactical errors. You need `if (x.split(" ")[1]).equals("+")` – ha9u63a7 Nov 10 '14 at 21:25
  • 2
    @user2177940 IMHO this is an artificial constraint and an extremely poor assignment. If you don't store the result of `split` in a variable then you will inevitably end up _repeating_ the split call to get the other elements. This is poor practise and violates the DRY ("Don't Repeat Yourself") principle. – Alnitak Nov 10 '14 at 21:28
  • You can't have two local parameters/variables with the same name. – Sotirios Delimanolis Nov 10 '14 at 21:28
  • @hagubear Look again. Your parentheses are in odd places. – Dawood ibn Kareem Nov 10 '14 at 21:34

2 Answers2

5

Well, what is returned is of type String[]. So if you know that there will be two items, you can reference it as an array..

if(x.split(" ")[1].equals("+"))

Extra Reading

Community
  • 1
  • 1
christopher
  • 26,815
  • 5
  • 55
  • 89
1

String.split returns an array, so this is how it could be done. Note the use of '.equals()'. In Java the == operator checks if the pointer value is the same.

if (x.split.(" ")[1].equals("+")) {
    // Do something
}

(And of course this could throw an out of bounds exception if the split wouldn't make an array of size >= 2)

David Conrad
  • 15,432
  • 2
  • 42
  • 54
eigil
  • 96
  • 4