What are String Methods?

String in Java (Concatenation)

  • Building longer strings from shorter strings
  • String concatenation operator +

Scanner Methods

  • next()
  • nextLine()

String are chars sequences

String gretting = "Hello!";
012345
Hello!

String Methods (CharAt)

Each char inside a String has an index number:

0123456789
chaRs here
  • The first char is always at index zero(0)
  • The charAt method returns a char at a given index inside a String
01234
Harry
public class greeting {
    public static void main(String[] args) {
    String greeting = "Harry";
    char start = greeting.charAt(0); 
    // H
    char last = greeting.charAt(4); 
    // y
  }
}

String Methods(length)

  • The length method returns the number of chars in the string
  • Example
public class name {
    public static void main(String[] args) {
    String name = "Bob Smith";
    System.out.print(name.length());
  }
}

Output:

9

String Methods (substring)

  • The substring(a, b) methods returns a portion of the String.

    • Staring at index a and ending before index b.
  • Example
012345678
Bob Smith
public class name {
    public static void main(String[] args) {
    String name = "Bob Smith";
    System.out.print(name.substring(2, 6));
  }
}

Output:

b Sm

String Methods(indexOf)

  • The indexOf(target) method returns start index of target in the String.

    • return -1 if target not in the string.
  • Example
012345678
Bob Smith
public class name {
    public static void main(String[] args) {
    String name = "Bob Smith";
    System.out.println(name.indexOf("b"));
    System.out.println(name.indexOf("x"));
  }
}

Output:

2

-1

String Methods(concat)

  • The concat method returns a new string that appends s2 to s1.
  • Example
public class name {
  public static void main(String[] args) {
    String s1 = "Hey";
    String s2 = "!!!";
    String output = s1.concat(s2);
    System.out.println(output);
  }
}

Output:

Hey!!!

文章目录