티스토리 뷰
day18 190315
String클래스의 API를 배웠습니다.
( 개인 사정으로 인해 포스팅이 밀리게 된 점 죄송합니다.
1~2일내에 밀린 포스팅을 전부 할 예정입니다.)
<Stirng>
-- StringBuilder
-- StringTokenizer (java.util)
: 문자열을 토큰화해서 사용하는 API
>> String text = "홍길동,김유신,강감찬";
String[] items = text.split(",")
>>토큰화과정(문자열들을 하나하나 토큰화해서 구분자를 준다.)
-주요 메소드
boolean hasMoreTokens()
다음에 꺼낼 토큰이 있으면 true를 반환한다.
String nextToken()
토큰을 하나 반환한다.
int countTokens()
토큰의 갯수를 반환한다.
--값을 여러개 담고 있는 클래스
: 배열, 콜렉션
for문으로 표현>> for (타입변수명 : 배열,콜렉션) { ...}
----
StringTokenizer
>> boolean hasMoreTokens()
String nextToken()
>> while x.hasMoreTokens()) {
String value = x.nextToken();
...
}
Enumeration
>> boolean hasMoreElements()
E nextElement()
>> while (x.hasMoreElements() {
E e = x.nextElement();
...
}
Iterator
>> boolean hasNext()
E next()
ResultSet
>> boolean next()
xxx getXXX(String name)
>> 위4개 while문으로 표현
while (조건식) {
수행문;
수행문;
}
조건식이 true일 때,
실행순서 : 조건식>수행문 >조건식>수행문
무한루프를 생성한다 >>
while(true) {
수행문;
수행문;
}
코딩tip!
String originalFilename = "홍길동.jpg";
String saveFilename = System.currentTimeMills() + originalFilename;
( 시간을 이름에 부여해서 무결성)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | package demo3; public class StringDemo1 { // String의 메소드들은 새로운 값을 만들어낸다. public static void main(String[] args) { String str1 = "hello world"; // String str1 = new String("hello world"); // String toUpperCase() : 소문자를 대문자로 변환해서 반환한다. // String toLowerCase() : 대문자를 소문자로 변환해서 반환한다. String result1 = str1.toUpperCase(); System.out.println("원본1 : " + str1); System.out.println("결과1 : " + result1); System.out.println("결과1 : " + str1.toUpperCase()); String result2 = result1.toLowerCase(); System.out.println("결과2 : " + result2); // String replace(String old, String new) : target에 지정된 문자를 새문자로 바꾼 새로운 문자열을 만들어서 반환한다. String str2 = "이것이 자바다. 자바 초급자를 위한 안내서"; String result3 = str2.replace("자바", "파이썬"); System.out.println("원본2 : " + str2); System.out.println("결과3 : " + result3); // int length() : 문자열의 길이를 반환한다. String str3 = "오늘 점심은 어떤거 먹지?"; int len = str3.length(); System.out.println("문자열의 길이 : " + len); // 공백 포함. // boolean equals(Object other) : 다른 문자열과 내용을 비교해서 동일한지 여부를 반환한다. // Object의 equals(Object other)을 재정의한 것 String name1 = new String("이순신"); String name2 = new String("이순신"); String name3 = ("이순신"); String name4 = ("이순신"); /* * 1. == 주소값 비교 * 2. equals() 내용비교 * * equals() 메소드는 String객체를 생성하는 방법에 상관없이 문자열의 내용이 동일하면 * true값을 반환한다. 따라서, 문자열의 비교는 반드시 equals() 메소드를 사용해야 한다. */ System.out.println(name1 == name2); System.out.println(name1.equals(name2)); System.out.println(name3 == name4); System.out.println(name3.equals(name4)); // String substring(int beginIndex) : beginIndex에서 끝가지 잘라낸 새로운 문자열을 반환한다. // String substring(int beginIndex, int endIndex) : beginIndex에서 endIndex앞까지 잘라낸 새로운 문자열을 반환한다. String str4 = "이것이 자바다"; String result5 = str4.substring(1); System.out.println("결과5 : " + result5); String result6 = str4.substring(2, 6); System.out.println("결과6 : " + result6); // boolean contains(String str) : 지정된 문자열이 포함되어 있는지 여부를 반환한다. String str5 = "이것이 자바다"; boolean result7 = str5.contains("자바"); System.out.println("결과7 : " + result7); // boolean startsWith(String str) : 지정된 문자열로 시작하는지 여부를 반환한다. // boolean endsWith(String str) : 지정된 문자열로 끝나는지 여부를 반환한다. String str6 = "http://www.daum.net"; String str7 = "www.google.com"; String str8 = "www.naver.com"; System.out.println("결과8 : " + str6.startsWith("http")); System.out.println("결과9 : " + str7.startsWith("http")); System.out.println("결과10 : " + str8.startsWith("http")); System.out.println("결과11 : " + str6.endsWith("com")); System.out.println("결과12 : " + str7.endsWith("com")); System.out.println("결과13 : " + str8.endsWith("com")); // boolean empty() : 문자열이 비어있으면 true를 반환합니다. String str9 = "자바다"; String str10 = " "; String str11 = ""; System.out.println("결과14: " + str9.isEmpty()); System.out.println("결과15: " + str10.isEmpty()); System.out.println("결과16: " + str11.isEmpty()); // String trim() : 문자열의 불필요한 좌우공백을 제거한 새로운 문자열을 반환한다. String str12 = " 이것이 자바다"; String result17 = str12.trim(); System.out.println("결과17: [" + result17 + "]"); // int indexOf(String str) : 지정된 문자열이 처음으로 등장하는 위치를 반환한다. String str13 = "이것이 자바다. 자바 입문용 추천 도서"; int result18 = str13.indexOf("자바"); int result19 = str13.indexOf("파이썬"); System.out.println("결과18: " + result18); System.out.println("결과19: " + result19); // char charAt(int index) : 지정된 위치의 글자를 반환한다. String str14 = "이것이 자바다"; char result20 = str14.charAt(1); System.out.println("결과: " + result20); // String split(String str) : 지정된 문자로 문자열을 자르고 배열에 담아서 반환한다. String str15 = "이순신,김유신,강감찬,홍길동,유관순"; String[] result21 = str15.split(","); System.out.println("결과21: " + result21[0]); System.out.println("결과21: " + result21[1]); System.out.println("결과21: " + result21[2]); System.out.println("결과21: " + result21[3]); System.out.println("결과21: " + result21[4]); // static String valueOf(int number) // static String valueOf(double number) // static String valueOf(boolean b) // 문자열로 변환해서 반환한다. String result22 = String.valueOf(3.14); System.out.println("결과22:" + result22); } } | cs |
>> 주석들을 참고하시고, 각 주석에 있는 API들을 코딩하셔서 실행창을 봐서 직접 확인해보시면 되겠습니다.
위 메소드들을 응용한 예제입니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | package demo3; import java.util.Scanner; public class StringDemo4 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("이름,국어,영어,수학 정보입력> "); String text = sc.next(); // 입력예 -> 홍길동,60, 80, 50 String[] values = text.split(","); System.out.println("이름: " + values[0]); System.out.println("국어: " + values[1]); System.out.println("영어: " + values[2]); System.out.println("수학: " + values[3]); sc.close(); } } | cs |
>> 10행처럼 입력을 양식에 맞게 넣고, 12행과 같이 코딩을 하면,
String배열에 [0]="홍길동", [1]="60" ... 과같이 저장됩니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | package demo3; import java.util.Scanner; public class StringDemo2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("비밀번호를 입력하세요: "); String pwd1 = sc.next(); System.out.print("비밀번호를 다시 입력하세요: "); String pwd2 = sc.next(); System.out.println(pwd1 == pwd2); System.out.println(pwd1.equals(pwd2)); sc.close(); } } | cs |
>> equals를 사용하게 되면 위 예제처럼, 문자열로 된 비밀번호를 일치여부를 판단할 수 있습니다.
16행과 같이 사용하시면 되겠습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | package demo3; import java.util.Scanner; public class StringDemo3 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("이메일을 입력하세요"); String email = sc.next(); int endIndex = email.indexOf("@"); String id = email.substring(0, endIndex); System.out.println("아이디:" + id); sc.close(); } } | cs |
>> 13행으로 @부분을 endIndex로 초기화하고, 14행에 substring을 사용하여 0부터 endIndex전까지를
id 변수로 선언하면, @앞의 부분을 아이디로 만드는 예를 만들 수 있습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | package demo4; public class StringBuilderDemo { public static void main(String[] args) { String title = "이것이 자바다"; String writer = "신용권"; int price = 30000; // String text = "제목:" + title + ", 저자:" + writer + ", 가격:" + price; StringBuilder sb = new StringBuilder(); sb.append("제목:"); sb.append(title); sb.append(", 저자:"); sb.append(writer); sb.append(", 가격:"); sb.append(price); String text2 = sb.toString(); System.out.println(text2); } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | package demo4; import java.util.StringTokenizer; public class StringTokenizerDemo { public static void main(String[] args) { StringTokenizer st = new StringTokenizer("김유신 강감찬 이순신 홍길동"); int count = st.countTokens(); System.out.println("토큰갯수 : " + count); while (st.hasMoreElements()) { String name = st.nextToken(); System.out.println(name); } StringTokenizer st2 = new StringTokenizer("100,20,50,28,59,9,17,83", ","); int total = 0; while (st2.hasMoreTokens()) { String value = st2.nextToken(); // 토큰 추출 "100" int number = Integer.parseInt(value); // 숫잔로 변환 100 total += number; // total에 누적 } System.out.println("합계: " + total); String text = "홍길동,010-1111-1111,,중앙HTA"; // 토큰과 배열의 차이점 (빈칸) String[] values = text.split(","); StringTokenizer st3 = new StringTokenizer(text, ","); System.out.println("배열의 길이: " + values.length); System.out.println("토큰의 길이: " + st3.countTokens()); } } | cs |
String API에서는 equals와 contains등이 자주 이용되니 각 API들의 기능을 숙지해두시는게 좋겠습니다.
금일에 과제로,
Lotto를 만드는 과제가 있었습니다.
1. 1~45난수 발생
2. 중복확인
3. 저장
4. if (position == 6)
break;
'Programming > JAVA' 카테고리의 다른 글
Java Web#18 자바 API (2) (0) | 2019.03.26 |
---|---|
JAVA Web#17 자바 API : Object (0) | 2019.03.18 |
JAVA Web#17 Day 17 Eclipse 설치 & 초기설정 (0) | 2019.03.18 |
JAVA Web#16 Day 16 중첩 클래스 & 익명 객체 (0) | 2019.03.15 |
JAVA Web#15 Day 15 인터페이스 (interface) (0) | 2019.03.14 |
- Total
- Today
- Yesterday
- h#
- Oracle
- Database
- html
- jhta
- 인라인엘리먼트
- 강제형변환
- spring
- 태그
- 오라클 문법
- 브라캣
- Class
- querybox
- 자바 기초
- 자바 국비
- 자바
- 자바 독학
- 국비
- 중앙HTA
- 프레임워크
- sql
- 데이터베이스
- copotter
- 이클립스
- block element
- 비등가조인
- 블록엘리먼트
- API
- 스프링
- inline element
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |