Methods of the String Class

There are some functions that are related to the String class so that we can easily work with the strings that we make in the code.

The indexOf Method

  • Returns the index of the character in the string in the form of an integer.
  • There are 4 types of indexOf methods.
    • indexOf ( char )
      • only takes a character and returns the index.
    • indexOf ( char , int fromIndex)
      • takes the character and also the position to start from.
    • indexOf ( string )
      • takes a string as the input and returns the starting index of the string.
    • indexOf ( string , int fromIndex )
      • takes the string and the position to start from.

capture

The charAt method

  • Returns the character of the string according to the given index. If the index does not exist, then it throws an exception.

capture2

The length Method

  • Returns the length of the string as an integer.

3

The concat Method

  • This concatenates the specified string to the end of the original string.

4

The replace Method

  • This replaces all the positions of the pointed character with the given character. This method is in 2 forms ( to replace one character or character sequence ).
    // Character replace
    String char_answer = text.replace('s','q');
    //Sequence of characters replace
    String seq_answer = text.replace("Blog","Web");

replace

The startsWith Method

  • Returns the boolean value if the text starts with the given character.
  • The parameters are case sensitive.
  • Also you can skip number of letters of the sequence before checking.
    //check from the beginning
    boolean answer1 = text.startsWith("t");
    //skip number of letters before cheking
    boolean answer3 = text.startsWith("P",8);

stw

The endsWith Method

  • Returns the boolean value if the text ends with the given character.

ewt

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s