ViRALiC
ViRALiC

Reputation: 1549

Save part of a String from a word to a different word

So, I'm still learning Java and I am curious about extracting information from Strings and and assigning the information to a variable.

Let's for example say, I have the following String:

{"my_books_are_all_organized","yes_sir_yes_they_are"}

Then I wish to make a new String that that only contains this part:

my_books

For example a String variable called whatIsOgranized, which only held the text "my_books", would have to gather all the information from the symbols:

{"

To the symbols:

_are

Everything in between those sets of symbols are to be stored in the whatIsOrganized String. So when I run:

System.out.println(whatIsOrganized);

It gives me:

my_books

Is this possible in Java? Could anyone show me how my above example would be coded?

Upvotes: 1

Views: 1573

Answers (2)

Aubin
Aubin

Reputation: 14863

The answer is yes, and the String class do it well.

I suggest to learn Java from the official tutorial, the chapter for Strings is here.

For a more powerful method to extract parts of string, the Regular Expressions may be used. The main class to deal with RE is java.util.regex.Pattern and their official tutorial is here. Another tutorial resource is here.

Upvotes: 3

Vivek
Vivek

Reputation: 1125

there is method in String Object in Java :

String substring(int beginIndex) Returns a new string that is a substring of this string. String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string.

which can be used as:

public class Test{
   public static void main(String args[]){
      String Str = new String("Welcome to Stackoverflow.com");

      System.out.print("Return Value :" );
      System.out.println(Str.substring(10) );

      System.out.print("Return Value :" );
      System.out.println(Str.substring(10, 15) );
   }
}

Return Value : Stackoverflow.com
Return Value : Stac

There are more ..depending on requirement.

Upvotes: 1

Related Questions