String 클래스의 주요 메서드

김정욱·2022년 12월 22일

공부📚

목록 보기
2/4
post-thumbnail

1. charAt(int index)

  • 해당 문자열에서 전달받은 index위치의 문자만을 추출해서 반환해주는 메소드
public class Main{
	public static void main(String[] args){
   
		String str = "Hello World";
		char ch = str.charAt(4);
		System.out.println(ch);
	}
}
---------------------------------------------------
👉 o

2. length()

  • 해당 문자열의 글자수를 반환해주는 메소드
public class Main{
	public static void main(String[] args){
   
		String str = "Hello World";
		int length = str.length();
		System.out.println(length);
	}
}
---------------------------------------------------
👉 11

3. substring(int beginIndex, int endIndex)

  • 해당 문자열의 전달받은 beginIndex부터 endIndex-1위치까지의 문자열을 추출해서 반환해주는 메소드
public class Main{
	public static void main(String[] args){
   
		String str = "Hello World";
		String res = str.substring(0, 3);
		System.out.println(res);
	}
}
----------------------------------------------<-------
👉 Hel

4. toUpperCase()

  • 해당 문자열을 다 대문자로 변환해서 반환해주는 메소드
public class Main{
	public static void main(String[] args){
   
		String str = "hello world";
		String res = str.toUpperCase();
		System.out.println(res);
	}
}
-----------------------------------------------------
👉 HELLO WORLD

5. toLowerCase()

  • 해당 문자열을 다 소문자로 변환해서 반환해주는 메소드
public class Main{
	public static void main(String[] args){
   
		String str = "HELLO WORLD";
		String res = str.toLowerCase();
		System.out.println(res);
	}
}
-----------------------------------------------------
👉 hello world

6. str.repeat(index)

  • 문자열 str을 index만큼 반복하는 메소드
public class Main{
	public static void main(String[] args){
   
		String str = "Hello World / ";
		String res = str.repeat(3);
		System.out.println(res);
	}
}
-----------------------------------------------------
👉 Hello World / Hello World / Hello World /

7. str1.indexOf(str2, int beginIndex)

  • 문자열 str1에서 문자열 str2와 일치하는 것을 찾는 메소드
    일치하면 시작점의 인덱스번호를 일치하는 문자열이 없으면 -1을 반환하는 메소드. postion은 검색을 시작할 위치이며 기본값은 0 이다.
public class Main{
	public static void main(String[] args){
   
		String str1 = "Hello World";
		String str2 = "orl";
		String str3 = "abc";

		int res1 = str1.indexOf(str2);
		int res2 = str1.indexOf(str3);

		System.out.println(res1 + ", " + res2);
	}
}
-----------------------------------------------------
👉 7, -1
profile
절박한 마음을 갖고 하루를 보내자!!

0개의 댓글