본문 바로가기
수업시간 JAVA/이론

substring/indexof/ lastindexof /split 만들어보기

by SEOKIHOUSE 2023. 4. 8.
package practice0404;

public class SubString {
	static String s = "hello hello world";

	public static void main(String[] args) {
		System.out.println(subString(1));
		System.out.println(subString(1, 3));
		System.out.println(indexof('l'));
		System.out.println(indexofs("lo"));
		System.out.println(lastindexof('h'));
	}

	public static String subString(int startIdx) {
		String result = "";
		for (int i = startIdx; i < s.length(); i++) {
			result = result + s.charAt(i);
		}
		return result;
	}
	
	public static String subString(int startIdx, int endIdx) {
		String result = "";
		for (int i = startIdx; i < endIdx; i++) {
			result = result + s.charAt(i);
		}
		return result;
	}
	
	//char일떄
	public static int indexof(char c) {
		int result = -1;
		for (int i = 0; i < s.length(); i++) { // 11
			if (s.charAt(i) == c) {
				result = i;
				break;
			}
		}
		return result;
	}
	
	//string일떄
	public static int indexofs(String c) {
		int result = -1;
		for (int i = 0; i < s.length(); i++) { // 11
			if (s.charAt(i) == c.charAt(0)) {
				if (s.substring(i, c.length() + i).equals(c)) {
					result = i;
					break;
				}
			}
		}
		return result;
	}

	public static int lastindexof(char c) {
		int result = -1;
		for (int i = s.length() - 1; i >= 0; i--) {
			if (s.charAt(i) == c) {
				result = i;
				break;
			}
		}
		return result;
	}

}
package practice0404;

public class splitpractice {

	public static void main(String[] args) {
		String s = "abcd-eftc-gsdg";
		String[] ss = s.split("-");
 		for(int i=0; i<ss.length; i++) {
 			System.out.println(ss[i]);
 		}
 		String result = ss[0] + ss[1] + ss[2];
 		System.out.println(result);
 		System.out.println("----------------");
 		System.out.println(split('-'));
	}
	
	
	public static String split(char a) {
		String s = "abcd-eftffc-gsasdg";
		String [] s2 =new String[3];
		int start =0;
		int count = 0;
		
		for(int i=0; i<s.length(); i++) {
			if(s.charAt(i) == a) {
				s2[count] = s.substring(start,i);
				start = i+1;
				count++;
			}
		}
		s2[count] =s.substring(start);
		String result = "";
		
		for(int i =0; i<s2.length; i++) {
			result = result +s2[i];
		}
		return result;
		
	}
}

'수업시간 JAVA > 이론' 카테고리의 다른 글

Interface  (0) 2023.04.09
상속  (0) 2023.04.08
싱글패턴/charAt문제  (0) 2023.04.08
trim / toLowerCase/ toUpperCase/ replace  (0) 2023.04.05
charAt()/indexof() /lastindexof() /concat/ substring()/ split/contains  (0) 2023.04.04