Java

String Methods

WebDevLee 2022. 2. 7. 22:40

자바에서 주로 쓰이는 문자열 메소드들에 대해 정리하였습니다.

 

 


< Introduction >

String is an object that represents a sequence of characters.

Because character strings are so vital to programming, Java assigned an entire class to them. 

String class has a lot of useful methods to help us. We don't have to import anything to use the String class because it's part of the java.lang package which is available by default.

 

 


< length() >

Returns the length ⁠— total number of characters ⁠— of a String.

 

Example)

String str = "Hello World!";  
 
System.out.println(str.length());
// 12

 

 


< concat() >

Concatenates one string to the end of another string.

 

  • Strings are immutable objects which means that String methods, like concat() do not actually change a String object.

 

Example)

String str = new String("Hello ");
 
str = str.concat("World!");
 
System.out.println(str);
// Hello World!

: str holds a reference to the String object, "Hello ". When use concat() on str, we changed its value so that it references a new object — "Hello World"

 

 


< equals() >

To test equality with strings

 

Example)

String flavor1 = "Mango";
String flavor2 = "Peach";
 
System.out.println(flavor1.equals("Mango"));
// prints true
 
System.out.println(flavor2.equals("Mango"));
// prints false

+. there’s also an equalsIgnoreCase( ) method that compares two strings without considering upper/lower cases.

+. there's also an compareTo( ) method that compares two strings lexicographically (think dictionary order).

 

 


< indexOf() >

To know the index of the first occurence of a character in a string

 

  • If the indexOf() doesn’t find what it’s looking for, it’ll return a -1

 

Example)

String letters = "ABCDEFGHIJKLMN";
System.out.println(letters.indexOf("C"));
// 2

String letters = "ABCDEFGHIJKLMN";
System.out.println(letters.indexOf("EFG"));
// 4

 

 


< charAt() >

Returns the character located at a String‘s specified index.

 

  • If try to return the character located out of string's index. It would produce an IndexOutOfBoundsException error

 

Example)

String str = "qwer";
 
System.out.println(str.charAt(2));
// e

 

 


< substring() >

To extract a substring from a string.

 

  • substring( ) need a two parameter:
    1. substring's begin index : inclusive
    2. (optional) substring's end index : exclusive

 

Example)

String line = "The Heav'ns and all the Constellations rung";
 
System.out.println(line.substring(24, 27));
// Prints: Con

 

 


< toUpperCase() / toLowerCase() >

  • toUpperCase(): returns the string value converted to uppercase
  • toLowerCase(): returns the string value converted to lowercase

 

Example)

String input = "Cricket!";
 
String upper = input.toUpperCase();
// stores "CRICKET!"
 
String lower = input.toLowerCase();
// stores "cricket!"