공백지우기 ( charAt, trim)

양혜정·2024년 1월 28일
0

Begin_java

목록 보기
34/71

공백지우기

1. charAt() 이용 - for

String str = "  korea   seou l 쌍용 강북 교육센터  ";
String str_result_for = "";

for(int i=0; i<str.length(); i++) {	// str.length() 길이를 나타냄
	if(str.charAt(i) != ' ')	{			// 공백이 아니면
    	str_result_for += str.charAt(i);	// 결과값에 입력
    }	// end of if----------
}	// end of for-----------------

2. charAt() 이용 - while

String str = "  korea   seou l 쌍용 강북 교육센터  ";
String str_result_while = "";

int i = 0;
while(i<str.length()) {
	if(str.charAt(i) != ' ')	{			// 공백이 아니면
    	str_result_while += str.charAt(i);	// 결과값에 입력
    }	// end of if-------
    i++;
}	// end of while------------

3. charAt() 이용 - do~while

String str = "  korea   seou l 쌍용 강북 교육센터  ";
String str_result_dowhile = "";

int i = 0;
do{
	if(str.charAt(i) != ' ')	{			// 공백이 아니면
    	str_result_dowhile += str.charAt(i);	// 결과값에 입력
    }	// end of if-------
    i++;
} while (!(i==str.length());	// end of do~while-----------

양쪽 공백 제거하기

.trim()

Ex)

System.out.println("       하       ".trim());		// 출력 : 하
System.out.println("       하   마  ".trim());		// 출력 : 하   마

모든 공백 제거 메소드 만들기

public static String space_delete(String input_str) {		
	String result = null;		// null 은 존재자체가 없다 / space Enter 놉!
	if(input_str != null) {	// null. 은 NullPointerException 에러 발생
		result = "";	// null.이 되지 않기때문에 초기값을 바꿔주어야 한다.
		for(int i=0; i<input_str.length(); i++) {	
			char ch = input_str.charAt(i);	// 1번 참고
				if( ch != ' ') 
					result += ch;	
		}	// end of for---------
	}	// end of if-----------------
	return result;
}	// end of public static String space_delete(String input_str)--------------

  • "" 안에 값이 공백인지 아닌지 확인하기
    isEmpty() -> true / false
System.out.println("              ".trim().isEmpty());		// 출력 : true
System.out.println("       하   마  ".trim().isEmpty());		// 출력 : false

정리

my.day08.a.spaceDelete -> Main_space_delete
my.day08.c.object_array -> Main_member
my.util -> MyUtil

0개의 댓글

관련 채용 정보