Substring in Java - how to split a sentence and store as different strings

I want to store part of the sentence (which is a string) to another string.

For example:

String s = " By 1889, central office operators were known as" hi-girls "due to the connection between greeting and telephone

I want to save "By 1889, central office operators were known as" one line

and

"hello-girls" because of the connection between the greeting and the phone "to another.

How to do it?

+3


source to share


4 answers


Try:

int index = s.indexOf("'hello-girls'");
System.out.println(s.substring(0, index ));
System.out.println(s.substring(index));

      

Output:



 By 1889, central telephone exchange operators were known as 
'hello-girls' due to the association between the greeting and the telephone 

      

Doc:

+3


source


Use the following code

    String s = " By 1889, central telephone exchange operators were known as 'hello-girls' due to the association between the greeting and the telephone ";
    int index=s.indexOf("'");
    String s1=s.substring(0,index);
    String s2=s.substring(index,s.length()-1);
    System.out.println(s1);
    System.out.println(s2);

      



See this ideon https://ideone.com/iB5quw

+2


source


If it's because of the word "hello-girls", you can do:

int index = s.indexOf("'hello-girls'"));

String firstPart = s.substring(0, index);
String secondPart = s.substring(index);

      

Note that the firstPart line will end with an empty space. You can easily remove it by changing the code above:

String firstPart = s.substring(0, index - 1);

      

+2


source


String s = " By 1889, central telephone exchange operators " +
            "were known as 'hello-girls' due to the association " +
            "between the greeting and the telephone ";

      

First way:

String[] strings = s.split("as ");

String first = strings[0] + "as";
// "By 1889, central telephone exchange operators were known as"

String second = strings[1];
// "'hello-girls' due to the association between the greeting and the telephone"

      

Second way:

String separator = " as ";
int firstLength = s.indexOf(separator) + separator.length();

String first = s.substring(0, firstLength);
// "By 1889, central telephone exchange operators were known as"

String second = s.substring(firstLength);
// "'hello-girls' due to the association between the greeting and the telephone"

      

+1


source







All Articles