본문 바로가기
수업 문제(국비 지원)/Java

[JAVA] 2022.09.09 - StringClass

by byeolsub 2023. 4. 29.

 ❓

문제 : 
 * 다음 결과가 나오도록 프로그램 수정하기
 * [결과]
 * basket
 * basketball
package chap11;

public class Test4 {
	public static void main(String[] args) {
		String str = "base"; 
		System.out.println(str.replace('e','k')+"et");
		str += "ball";
		System.out.println(str);
	}
}

문제 : 
[결과] 
 HTML=>홍길동
 CSS=>김삿갓
 JavaScript=>이몽룡
 JAVA=>성춘향
 JSP=>임꺽정
 스프링=>향단이
package chap11;

public class Test5 {
	public static void main(String[] args) {
		String s1 = "HTML-CSS-JavaScript-JAVA-JSP-스프링";
		String s2 = "홍길동  ,  김삿갓,  이몽룡, 성춘향,  임꺽정, 향단이    ";
		int i =0;
		String [] arr1 = s1.split("-");
		String [] arr2 = s2.split(",");
		for(i=0;i<arr1.length;i++){
			for(i=0;i<arr2.length;i++){
			System.out.println(arr1[i]+"=>"+arr2[i].trim());
			}
		}
	}
}
방법2

public class Test5 {
	public static void main(String[] args) {
		String s1 = "HTML-CSS-JavaScript-JAVA-JSP-스프링";
		String s2 = "홍길동  ,  김삿갓,  이몽룡, 성춘향,  임꺽정, 향단이    ";
		
		String[] arr1 = s1.split("-");
		//\\\\s* : 공백 0개이상 정규식. 
		String[] arr2 = s2.split("\\\\s*,\\\\s*"); //공백 콤마 공백을 기준으로 spilt
		for(int i=0;i<arr1.length;i++) {
			System.out.println(arr1[i]+"=>"+arr2[i]);
		}
	}
}

 

 💡 \\s* : 공백 0개 이상 정규식.


 ❓

문제 : 
 * 문자열 1,234를 정수로 변경하여  * 10 한 값을 세자리마다 , 찍어 출력하기
 * [결과]
 *  12,340
package chap11;

public class Test6 {
	public static void main(String[] args) {
		String str = "1,234";
		str = str.replaceAll(",","");
		//System.out.println(str); 문자열 함수는 값을 바꾸지 않고 
		//값만 반환한다 그러므로 변수에 값을 넣어주어야 함
		Integer num = Integer.parseInt(str);
		num*=10;
		System.out.printf("%,3d",num);
	}
}

  • 방법 2 :
1. str = str.replaceAll(",",""); 을  Integer.parseInt()안에 집어넣어 num 표현

2. string.format으로 문자열형식화하여 출력
3. 또는 prinf로 같은 2.와 같은 방법으로 출력
법2

package chap11;

public class Test6_A {
	public static void main(String[] args) {
		String str = "1,234";
		int num = Integer.parseInt(str.replace(",","")); //1234 숫자
		System.out.println(String.format("%,d", num*10));
		System.out.printf("%,d\\n", num*10);		
	}
}

문제 : 
다음의 결과가 나오도록 프로그램을 수정하기
[결과]
fullPath:c:/jdk17/work/Test.java
path:c:/jdk17/work
fileName:Test.java
package chap11;

public class Test7 {
	public static void main(String[] args) {
		String fullPath = "c:/jdk17/work/Test.java";
		String path="";
		String fileName = "";
		System.out.println("fullPath:" + fullPath);
		System.out.println("path:" + fullPath.substring(0,13));
		System.out.println("fileName:" + fullPath.substring(14,23));
	}
}

  • lastIndexOf("/") : 뒤쪽 우선 / 의 위치인덱스 리턴 사용
package chap11;

public class Test7_A {
	public static void main(String[] args) {
		String fullPath = "c:/jdk17/work/Test.java";
		String path="";
		String fileName = "";

		//lastIndexOf("/") : 뒤쪽 우선 / 의 위치인덱스 리턴
		int idx = fullPath.lastIndexOf("/"); //마지막 /의 인덱스 값 
		path = fullPath.substring(0,idx); //c:/jdk17/work
		fileName = fullPath.substring(idx+1); //Test.java
		
		System.out.println("fullPath:" + fullPath);
		System.out.println("path:" + path);
		System.out.println("fileName:" + fileName);
	}
}

문제 : 
* 다음 결과가 나오도록 정의된 메서드를 구현하기
* 메서드명 : fillZero
* 기능 : 주어진 문자열(숫자)로 주어진 길이의 문자열로 만들고, 
*        왼쪽 빈 공간은 0으로 채운다.
*        만일 주어진 문자열이 null이거나 
*        문자열의 길이가 length의 값과 같으면 그대로 반환한다.
*        만일 주어진 length의 값이 0과 같거나 작은 값이면 
*        빈 문자열("")을 반환한다.
* 반환타입 : String
* 매개변수 : String src, int length

[결과]
0000012345

123
null
package chap11;

public class Test8 {
	public static void main(String[] args) {
		  String src = "12345";
		  System.out.println(fillZero(src, 10));
		  System.out.println(fillZero(src, -1));
		  System.out.println(fillZero(src, 3));
		  System.out.println(fillZero(null, 3));
	}
	static String fillZero(String src, int length) {
		String zero="";
		if(src == null || length == src.length()) {
			return src;
		}
		else if(length<=0) {
			return "";
		}
		else if(length<src.length()) {
			return src.substring(0, length);
		}
		else {
			for(int i=0; i<length-src.length(); i++) {
				zero += '0';
			}
			return zero + src;
		}
		
	}
}
public class Test8_A {
	public static void main(String[] args) {
		  String src = "12345";
		  System.out.println(fillZero(src, 10));
		  System.out.println(fillZero(src, -1));
		  System.out.println(fillZero(src, 3));
		  System.out.println(fillZero(null, 3));
	}
	 static String fillZero(String str,int len) {
		 if(str == null) return null;
		 if(len <= 0) return "";		 
		 if(str.length() >= len) 
			   return str.substring(0,len);

		 int num = Integer.parseInt(str);
		 return String.format("%010d",num);
	 }
	
}
public class Test8_A {
public static void main(String[] args) {
		  String src = "12345";
		  System.out.println(fillZero(src, 10));
		  System.out.println(fillZero(src, -1));
		  System.out.println(fillZero(src, 3));
		  System.out.println(fillZero(null, 3));
	}
	static String fillZero(String str,int len) {
		if(str == null) return null;
		if(len <= 0) return "";		 
		if(str.length() >= len) 
			  return str.substring(0,len);
		
		StringBuffer sb = new StringBuffer(); //동적으로 크기를 잡아 버퍼 생성
		for(int i=0;i<str.length();i++) { 
			sb.append(0); //0을 포문조건식 str길이(=src)만큼 추가
		}
		sb.replace(len-str.length(), len, str); // 0000012345
		//replace(시작위치, 끝나는위치, 문자열) 
		//인덱스5번째자리부터 10번째자리까지 문자열str로 교체하겠다.
		return sb.toString();
	}	
}

</aside>

<aside> ❓

문제 : 
* int getRand(f,t) : 함수 구현하기
 *   f ~ t 또는 t~ f 까지  범위에 숫자를 임의의 수로 리턴하는 함수
 *   f, t 값은 포함됨. 
 *   1 ~ 10 난수 (int)(Math.random() * (10-1 +1))  + 1
public class Test9 {
	public static void main(String[] args) {
		for (int i = 0; i < 20; i++) {
			System.out.print(getRand(1, -3) + ",");
		}
		System.out.println();

		for (int i = 0; i < 20; i++) {
			System.out.print(getRand(-1, 3) + ",");
		}
	}

	static int getRand(int f, int t) {
		int i = (int) (Math.random() * (10)) + 1; //1~10까지난수
		if (i <= f || i >= t) { //i가 f보다작거나같고, t보다 크거나 같을때
			i = (int) (Math.random() * (f - t + 1)) + t;
			**//(Math.random() * (최대값-최소값+1))+최소값(가장작은값표시)**
			return i;
		} else if (i >= f || i <= t) { //i가 t보다작거나같고, f보다 크거나 같을때
			i = (int) (Math.random() * (t - f + 1)) + f;
			return i;
		}
		return i;
	}
}

  • Math라이브러리 사용
package chap11;

public class Test9_A {
	public static void main(String[] args) {
		for(int i=0;i<20;i++) {
			System.out.print(getRand(1,-3)+",");
		}
		System.out.println();
		for(int i=0;i<20;i++) {
			System.out.print(getRand(-1,3)+",");
		}
	}
	static int getRand(int f,int t) {
		int min = Math.min(f,t);
//		int min = (f > t)?t:f;
		int max = Math.max(f,t);
		int cha = max - min; //최대값에서 최소값을 뺌
		return (int)(Math.random() * (cha+1)) + min;
		//
	}
	
}

💡 return (int)(Math.random() * (max - min+1)) + min; +1해주는 이유

           : 최대값-최소값 최대값자리가 하나빠짐. <=까지 포함해야하므로

             ex) 1~10자리 10-1=9 9개 최소값1부터 9개여서 +1 10까지 포함해주기


💡 Math.min(a,b); 라이브러리 메소드 설명.

                              : 둘 중 더 작은 값을 리턴한다.

      Math.max(a,b); :a와 b 둘 중 더 큰 수를 리턴한다

* @param   a   an argument.
* @param   b   another argument.
* @return  the smaller of {@code a} and {@code b}.

public static int min(int a, int b) {
  return (a <= b) ? a : b; 
}

문제 : 
<aside>
문자 중에서 ‘a'부터 ’z'까지가 각각 몇 개 존재하는지 비율을 조사하시오.
단 대문자는 소문자로 인식하여 처리한다.**

* I am honored to be with you today at your commencement 
 * from one of the finest universities in the world. 
 * I never graduated from college. Truth be told, 
 * this is the closest I've ever gotten to a college graduation. 
 [결과]
a -> 8 ,  4.706%
b -> 2 ,  1.176%
c -> 5 ,  2.941%
d -> 7 ,  4.118%
e -> 25 , 14.706%
f -> 4 ,  2.353%
g -> 5 ,  2.941%
h -> 7 ,  4.118%
i -> 12 ,  7.059%
j -> 0 ,  0.000%
k -> 0 ,  0.000%
l -> 7 ,  4.118%
m -> 6 ,  3.529%
n -> 10 ,  5.882%
o -> 19 , 11.176%
p -> 0 ,  0.000%
q -> 0 ,  0.000%
r -> 11 ,  6.471%
s -> 7 ,  4.118%
t -> 20 , 11.765%
u -> 6 ,  3.529%
v -> 4 ,  2.353%
w -> 2 ,  1.176%
x -> 0 ,  0.000%
y -> 3 ,  1.765%
z -> 0 ,  0.000%

</aside>
package chap11;

public class Test10_A {
	public static void main(String[] args) {
		String msg = 
	"I am honored to be with you today at your commencement "
	+ "from one of the finest universities in the world. "
	+ "I never graduated from college. Truth be told, "
	+ "this is the closest I've ever gotten to a college graduation.";
		msg = msg.toLowerCase();
		int chcnt=0;
		int cnt[]=new int[26];
		char ch;
		for(int i=0; i<msg.length( ); i++) {
		  if(msg.charAt(i)>='a'&& msg.charAt(i)<='z') {
		     cnt[msg.charAt(i)-'a']++;
		     chcnt++;
		  }   
		}   
		for(int i=0; i<26; i++){
		     ch=(char)('a'+i);
		     System.out.printf
		     ("%c -> %d , %6.3f%c\\n",ch,cnt[i],(cnt[i]*100.0/chcnt),'%');
		     System.out.println
		     (ch+" => "+cnt[i] +" , " + String.format("%6.3f",cnt[i]*100.0/chcnt)+'%');
	      }
	}		  
}