-1

I have a variable inside of a String. Now I need to take that Variable from the string and split it so it only take that part and store it in a new variable so I can print just that variable. (I'm sorry if its a rough explanation I'm new and phrasing things is still tricky)

fisrtName is the users input

String FIRST_SENTENCE = " There once was a person named " + firstName + " who lived in a city called " + city + ". ";

//there are other strings and variables but this is basically the important part

String nameOne = FIRST_SENTENCE.split(firstName);
System.out.println(nameOne);

All I need is for the println to output (firstName) aka (userInput)

Bishan
  • 15,211
  • 52
  • 164
  • 258
kubakyc
  • 17

4 Answers4

3

split

returns an array and not String. You have to store the result of split inside an Array.

try this:

String[] nameOne = FIRST_SENTENCE.split(firstName);
hiren
  • 1,067
  • 1
  • 9
  • 16
1

Since you already have access to the userInput, You can simply use below code to print it.

System.out.println(firstName);

If you need to get the userInput from the generated String, Use this method.

private String getFirstName(String firstSentence, String leftWord, String rightWord)
{
    return firstSentence.substring(firstSentence.indexOf(leftWord) + leftWord.length(), 
        firstSentence.indexOf(rightWord));
}

String nameOne = getFirstName(FIRST_SENTENCE, "named", "who");
System.out.println(nameOne);
Bishan
  • 15,211
  • 52
  • 164
  • 258
0

You are getting the error because you are trying to assign an array of Strings to String.

String nameOne = FIRST_SENTENCE.split(firstName); // Illegal

The split method the array of strings computed by splitting this string around matches of the given regular expression. You can modify the code like this to make it legal:

String[] splits = FIRST_SENTENCE.split(firstName);

This will give you an array of length 2 with two values like this: [ There once was a person named , who lived in a city called <your city name here>. ] Please note you are not going to get the value of firstName by doing this unnecessary split if you are planning to use that from split result. You already have a firstName handy, use that instead.

1218985
  • 7,531
  • 2
  • 25
  • 31
0
String[] nameOne = FIRST_SENTENCE.split(firstName);

First of all split() method will always result in String[]. By using split() method on firstname you would never be able to print firstname, what it does is it breaks the String around the first name, as a result, the output will be String[] of length 2 with values :

[ There once was a person named, who lived in a city called <city>. ]
Bhargav
  • 51
  • 4