자바

JAVA STEP 22. String 문자열

IT의 큰손 2023. 2. 15. 22:25
728x90

★ 문자열 ( String)

  • 문자의 집합

1. 문자열 길이

  • int length()
  •  
		System.out.println(name1.length());		//문자열 길이
		System.out.println(name2.length); 		//배열 길이
		
		System.out.println("홍길동".length());
		
		System.out.println("홍A1.".length());
		
		//요구사항] 이름 입력 > 몇글자?
		Scanner scan = new Scanner(System.in);
		
		System.out.println("이름 : ");
		
		String name = scan.nextLine();
		
		System.out.println(name.length());

		//유효성 검사(2~5자 이내)
		if(name.length() >= 2 && name.length() <=5) {
			System.out.println("올바른 이름");
		} else {
			System.out.println("이름은 2~5자 이내로 입력!!");
		}

 

2. 문자열 추출

  • charAt(int index)
  • 원하는 위치의 문자를 추출하는 메소드
  •  
		//문자열 추출
		//- char charAt(int index)
		//- 원하는 위치의 문자를 추출하는 메소드
		//- zero-based Index
		
		//			0 1 2 3 4567 8 9 10
		String txt = "안녕하세요. 홍길동님";

		char c = txt.charAt(3);
		System.out.println(c);
		
		c = txt.charAt(7);
		System.out.println(c);
		
//		//java.lang.StringIndexOutOfBoundException : index 11, length 11 에러.(즉, 10까지 있는데 11이라해서 에러 발생)
//		c = txt.charAt(11);
//		System.out.println(c);
	
		//마지막 문자
		c = txt.charAt(txt.length()-1);
		System.out.println(c);

 

3. 문자열 공백 제거

  • String trim()
  • 문자열에 존재하는 공백을 제거하는 작업
  •  
public static void m4() {
		
		//문자열 공백 제거
		//- String trim()
		//- 문자열에 존재하는 공백(Whitespace > 스페이스, 탭. 개행)을 제거하는 메소드
		//- 문자열의 시작과 끝에 있는 공백을 제거
		
		String txt = "		하나		둘		셋		";
		
		System.out.println(txt);
		
		System.out.printf("[%s]\n", txt);
		System.out.printf("[%s]\n", txt.trim());
		
		String s1 = "자바";
		String s2 = "  자바  ";
		
		System.out.println(s1.equals(s2));
		
	}//m4()

 

4. 문자열 검색

  • boolean contains(String)
  • 문자열에 찾고자하는 문자열이 있는지 검색
public static void m5() {
		
		//문자열 검색
		//- boolean contains(String)
		//- 문자열에 찾고자하는 문자열이 있는지 검색 (true/false)
		
		String txt = "홍길동님 안녕하세요.";
		
		//boolean contains(CharSequence s) //문자열 넣어도 된다는 뜻
		System.out.println(txt.contains("홍길동"));
		System.out.println(txt.contains("아무개"));
		
		System.out.println("950215-2012457".contains("-"));
		
	}//m5()

 

5. 문자열 검색

  • int indexOf(char c)
  • int indexOf(String s)
  • int indexOf(char c, int beginIndex)
  • int indexOf(String s, int beginIndex)
  • int lastindexOf(char c)
  • int lastindexOf(String s)
  • int lastindexOf(char c, int beginIndex)
  • int lastindexOf(String s, int beginIndex)
  •  
public static void m6() {
		
		//문자열 검색
		// 문자열의 위치를 반환해주는 역할
		//- int indexOf(char c)
		//- int indexOf(String s)
		//- int indexOf(char c, int beginIndex)
		//- int indexOf(String s, int beginIndex)
		//- int lastindexOf(char c)
		//- int lastindexOf(String s)
		//- int lastindexOf(char c, int beginIndex)
		//- int lastindexOf(String s, int beginIndex)
		
		String txt = "안녕하세요. 홍길동입니다.";
		
		int index = -1;
		
		index = txt.indexOf("홍");
		System.out.println(index);
		
		index = txt.indexOf("하");
		System.out.println(index);
		
		index = txt.indexOf("홍길동");
		System.out.println(index);
		
		index = txt.indexOf("홍길순"); //완전일치할때만 찾아주기 때문에 불가능함 >-1
		System.out.println(index);
		
		txt = "안녕하세요. 홍길동입니다.";
		index = 0;
		while (true) {
			
			index = txt.indexOf("홍길동", index);
			
			if(index == -1) {
				break;
			}
			System.out.println(index); //7
			
			index = index + 3;
			
		}
		
//		index = txt.indexOf("홍길동", 0);
//		System.out.println(index); //7
//		
//		index = txt.indexOf("홍길동", 10);
//		System.out.println(index); //21
//		
//		index = txt.indexOf("홍길동", 24);
//		System.out.println(index); //
		
		txt = "안녕하세요. 홍길동입니다. 반갑습니다 홍길동입니다. 네 홍길동입니다.";
		
		//검색방향
		System.out.println(txt.indexOf("홍길동", 10));		//왼쪽 > 오른쪽
		System.out.println(txt.lastIndexOf("홍길동", 30));	//오른쪽 > 왼쪽
	}//m6()

 

6. 금지어 변경 알고리즘

    •  
public static void m7() {
		
		//SNS, 게시판 > 금지어!!
		
		String content = "안녕하세요, 저는 자바를 배우는 학생입니다.";
		String word = "바보"; //금지어
		
		if(content.contains(word)) {
			System.out.println("금지어 발견!!");
		} else {
			System.out.println("글쓰기 진행..");
		}
		
		if(content.indexOf(word) > -1) {
			System.out.println("금지어 발견!!");
		} else {
			System.out.println("글쓰기 진행..");
		}
		
		
		content = "안녕하세요. 멍청이 바보 저는 자바를 배우는 학생입니다.";
		String[] words = {"바보", "멍청이", "메롱"};
		for (int i=0; i<words.length; i++) {
			
			if(content.indexOf(words[i]) > -1) {
				System.out.println("금지어 발견!!!");
				break; //**
			}
		} System.out.println("완료");
		
		//주민등록번호 > "-"
		
		String jumin = "950215-2012457";
		if(jumin.charAt(6)=='-') {
			System.out.println("O");
		}else {
			System.out.println("X");
		}
		
		if(jumin.indexOf("-") == 6) {
			System.out.println("O");
		} else {
			System.out.println("X");
		}
	}//m7()

 

7. 문자열 대소문자 변경

  • String toUpperCase() > 문자열을 모두 대문자로 변환
  • String toLowerCase() > 문자열을 모두 소문자로 변환
  •  
public static void m8() {
		
		//문자열 대소문자 변경
		//- String toUpperCase() > 문자열을 모두 대문자로 변환
		//- String toLowerCase() > 문자열을 모두 소문자로 변환
		
		String content = "오늘 수업은 String Method입니다.";
		String word = "string";
		
		if(content.indexOf(word) > -1) {
			System.out.println("O");
		}else {
			System.out.println("X");
		}
		
		System.out.println(content.toUpperCase());
		System.out.println(content.toLowerCase());
		
		System.out.println("Java".equals("java")); //false
		System.out.println("Java".toUpperCase().equals("java".toUpperCase())); //true
	}//m8()

 

8. 패턴 검색

  • boolean starsWith(String)
  • boolean endsWith(String)
  •  
public static void m9() {
		
		//패턴 검색
		//- boolean starsWith(String)
		//- boolean endsWith(String)
		
		String txt = "자바 개발자 과정";
		
		System.out.println(txt.startsWith("자바")); 		//해당 문자열이 자바 라는 글자로 먼저 시작되나요? true
		System.out.println(txt.startsWith("오라클"));
		System.out.println(txt.indexOf("자바")==0);
		
		System.out.println(txt.endsWith("과정"));			//해당 문자열이 과정 이라는 글자로 끝나나요? true
		System.out.println(txt.endsWith("교육"));			
		System.out.println(txt.indexOf("과정") == txt.length()-2);
		
		//파일 조작
		String file = "Ex36_String.java";
		
		//해당 파일의 확장자가 ".java" 인지 확인?
		if(file.endsWith(".java")) {
			System.out.println("확장자가 자바 파일입니다.");
		}else {
			System.out.println("확장자가 자바 파일이 아닙니다.");
		}
		
	}//m9()

 

 

9.문자열 추출

  • String subString(int beginIndex, int endIndex)
  • String subString(int beginIndex)
  •  
public static void m10() {
		
		//문자열 추출
		//- String subString(int beginIndex, int endIndex)
		//- String subString(int beginIndex)
		
		String txt = "가나다라마바사아자차카타파하";
		
		System.out.println(txt.substring(3, 7)); // 3~6
		System.out.println(txt.substring(5, 6)); // 5~5 >> 문자열 "바"
		System.out.println(txt.charAt(5)); // 5~5		>> 문자형 '바'
		System.out.println();
		
		//정형화된 데이터
		String jumin = "950215-2012365";
		
		//몇년생?
		System.out.println(jumin.substring(0,2));
		
		//몇월생?
		System.out.println(jumin.substring(2,4));
		
		//몇일생?
		System.out.println(jumin.substring(4,6));
		
		//성별?
		System.out.println(jumin.substring(7,8));
		
		//파일 경로 > 파일명?
		String path = "/Users/kimdaehwan/Desktop/class/code/java/JavaTset/src/com/test/java/Ex36_String.java";
		
		int index = path.lastIndexOf("/");
		System.out.println(index);
		
		String filename = path.substring(index+1);
		System.out.println(filename);
		
		//확장자 없는 파일명 추출
		index = filename.lastIndexOf(".");
		
		String filenameWithoutExtension = filename.substring(0, index);
		System.out.println(filenameWithoutExtension);
		
		//확장자 추출
		String extension = filename.substring(index);
		System.out.println(extension);
		
		
	}//m10()

 

10. 문자열 치환(바꾸기)

  • String replace(String old, String new)
  • 문자열의 일부를 다른 문자열로 교체하는 메소드
  •  
public static void m11() {
		
		//**** 모든 문자열 메소드는 원본을 수정하지 않는다!!!
		
		//문자열 치환(바꾸기)
		//- String replace(String old, String new)
		//- 문자열의 일부를 다른 문자열로 교체하는 메소드
		
		String txt = "안녕하세요. 홍길동입니다.";
		
		System.out.println(txt.replace("홍길동", "아무개")); //문자열을 바꾸는 것 
		
		String content = "게시판에 글을 작성합니다. 바보야!!";
		String word = "바보";
		
		//금지어 안보이게 처리 > Masking
		System.out.println(content.replace(word, "**"));
		
		//replace에서 ""(빈문자열)로 바꾸기 > 원하는 문자열을 삭제
		System.out.println(content.replace(word, ""));
		
	}

 

11. 문자열 분리

  • split(String delimiter)
  • 구분자를 기준으로 문자열을 자르는 메소드
  •  
public static void m12() {
		
		//문자열 분리
		//- split(String delimiter)
		//- 구분자를 기준으로 문자열을 자르는 메소드
		
		String name = "홍길동,아무개,하하하";
		
		String[] list = name.split(","); //구분자는 사라짐
		
		for(int i=0; i<list.length; i++) {
			System.out.println(list[i] + "," + list[i].length());
		}
	}//m12()

 

728x90