Intellij를 사용하여 테스트 해보았습니다. 주 언어가 Java인 프로그래머나 개발자라면 String클래스와 관련하여 기본적인 부분을 익혀야 합니다.

String과 관련하여 여러 method를 만들어봤으니 주석을 하나하나 풀어보며 실행시켜서 테스트해보시고 이해하도록 노력해보시기 바랍니다.


/**
* Created by 진우 on 2016-07-10.
*/
public class MyStringTest {
public static void main(String[] args) {
MyStringTest test = new MyStringTest();
test.constructors();
//System.out.println(test.nullCheck(null)); //Return -> true
//System.out.println(test.nullCheck("hello")); //Return -> false
//test.compareCheck(); //Return -> Length of Text, isEmpty of Text
//test.equalCheck();
//test.compareToCheck();
//test.addressCheck();
//test.matchCheck();
//test.indexOfCheck();
//test.lastIndexOfCheck();
//test.substringCheck1();
//test.splitCheck();
//test.trimCheck();
//test.replaceCheck();
//test.formatCheck();
}

public void constructors() {
try {
String src = "대한민국";

// java파일 기본 encoding
System.out.println("file encoding : " + System.getProperty("file.encoding"));

// 기본 encoding의 바이트 배열
byte[] bytearray = src.getBytes();

System.out.println();
System.out.println("기본 encoding 문자열 길이 : "+new String(bytearray).length());
System.out.println("기본 encoding 바이트 길이 : "+bytearray.length);
System.out.println("기본 encoding 문자열 : "+new String(bytearray));
System.out.println();

// euc-kr encoding의 바이트 배열
byte[] euckrbyte = src.getBytes("euc-kr");
System.out.println("euc-kr 문자열 길이 : "+new String(euckrbyte).length());
System.out.println("euc-kr 바이트 길이 : "+euckrbyte.length);
System.out.println("euc-kr 문자열 : "+new String(euckrbyte));

/*
String::getBytes 는 자바 내부에 관리되는 유니코드 문자열을 인자로 지정된 캐릭터셋의 바이트 배열로 반환하는 메서드이며,
new String(바이트배열, 캐릭터셋) 생성자는 해당 바이트 배열을 주어진 캐릭터 셋으로 간주 하여 스트링을 만드는 생성자입니다.

흔히 할 수 있는 실수로, 캐릭터 변환이랍시고 new String(바이트배열, 변환하고싶은 희망사항 캐릭터셋) 을 쓰는 오류가 있을 것입니다.
자바 내부에서 처리하는 문자열은 일괄적으로 같은 유니코드 형식으로 처리되며,
이기종 전송 등 필요한 경우에는 getBytes()로 해당 문자열 바이트 배열로 변환 뒤 전송하면 그만일 것입니다.
다만 예전 구형 웹서버등을 사용한 프로젝트의 경우의 문자열을 원래 캐릭터로 복구하는 코드가 위의 new String 을 쓰는 경우가 있는데,
이건 웹 서버에서 캐릭터셋을 잘못 해석하여 주는 것을 바로잡는 코드이거나, 비슷한 캐릭터 코드에서 코드로 해석한 것이며, 캐릭터 셋 변환이 아님을 알아둡시다.
*/
////////////////////////////////////////

String str = "한글";
//"한글" 의 str값에 따라서 아래 출력이 바뀜. EUC-KR은 한자에 2Byte씩, UTF-16은 한자에 3Byte씩.

byte[] array1 = str.getBytes();
printByteArray(array1);
String str1 = new String(array1);
System.out.println(str1);

byte[] array2 = str.getBytes("EUC-KR");
printByteArray(array2);
String str2 = new String(array2, "EUC-KR");
System.out.println(str2);

byte[] array3 = str.getBytes("UTF-16");
printByteArray(array3);
String str3 = new String(array3, "UTF-16");
System.out.println(str3);
}
catch(Exception e) {
e.printStackTrace();
}
}

public void printByteArray(byte[] array) {
for(byte data:array) {
System.out.print(data + " ");
}
System.out.println();
}
////////////////////////////////////////////////////////

public boolean nullCheck(String text) {
if(text == null)
return true;
else
return false;
}

////////////////////////////////////////////////////////

public void compareCheck() {
String txt = "You must know String class";
System.out.println("Length of Text = " + txt.length());
System.out.println("isEmpty of Text=" + txt.isEmpty());
}

////////////////////////////////////////////////////////

public void equalCheck() {
String text = "Check value";
//String text2 = "Check value";
String text2 = new String("Check value"); //새로운 String 객체 생성
if(text == text2)
System.out.println("text == text2 result is same.");
else
System.out.println("text == text2 result is different.");

if(text.equals("Check value"))
System.out.println("text.equals(text2) result is same.");
else
System.out.println("text.equals(text2) result is different.");

String text3 = "check value";
if(text.equalsIgnoreCase(text3))
System.out.println("text.equalsIgnoreCase(text3) result is same.");
else
System.out.println("text.equalsIgnoreCase(text3) result is different.");
}

////////////////////////////////////////////////////////

public void compareToCheck() {
String text="A";
String text2="B";
String text3="C";

System.out.println(text2.compareTo(text));
System.out.println(text2.compareTo(text3));
System.out.println(text.compareTo(text3));

/*
compareTo 메소드는 정렬할때 사용하게되는데, true, false의 결과가 아니라,
비교하려는 매개변수로 넘겨준 String 객체가 알파벳순으로 앞에있으면 양수를,
뒤에있으면 음수를 리턴합니다. 알파벳 순서만큼 그 숫자값은 커지게 됩니다.
*/
}

////////////////////////////////////////////////////////

public void addressCheck() {
String addresses[] = new String[] {
"It is test String Class",
"why are not you test String",
"It is very important thing of Class",
};
int startCount=0, endCount=0, containCount=0;
String startText="It";
String endText="Class";
String containText="test";

for(String address:addresses) {
if(address.startsWith(startText)) {
startCount++;
}
if(address.endsWith(endText)) {
endCount++;
}
if(address.contains(containText)) {
containCount++;
}
}
System.out.println("Starts with - " + startText + " - count is " + startCount);
System.out.println("Ends with - " + endText + " - count is " + endCount);
System.out.println("Contains with - " + containText + " - count is " + containCount);
}

////////////////////////////////////////////////////////

public void matchCheck() {
String text = "This is a text";
String compare1 = "is";
String compare2 = "this";
System.out.println(text.regionMatches(2, compare1, 0, 1));
//매개변수가 4개인 메소드
System.out.println(text.regionMatches(5, compare1, 0, 2));
//매개변수가 4개인 메소드
System.out.println(text.regionMatches(true, 0, compare2, 0, 4));
//매개변수가 5개인 메소드

/* (regionMatches 메소드 매개변수 설명)
*
* ignoreCase : true일 경우 대소문자 구분을 하지 않고, 값을 비교
* toffset : 비교 대상 문자열의 확인 시작 위치를 지정
* other : 존재하는지를 확인할 문자열을 의미
* ooffset : other 객체의 확인 시작 위치를 지정
* len : 비교할 char의 개수를 지정
*/
}

////////////////////////////////////////////////////////
//index 위치를 return값으로 받습니다. 없다면 -1
public void indexOfCheck() {
String text="Java technology is both a programming language and a platform.";
System.out.println(text.indexOf('a'));
System.out.println(text.indexOf("a "));
System.out.println(text.indexOf('a', 20));
System.out.println(text.indexOf("a ", 20));
System.out.println(text.indexOf('z'));
}

////////////////////////////////////////////////////////
public void lastIndexOfCheck() {
String text="Java technology is both a programming language and a platform.";
System.out.println(text.lastIndexOf('a'));
System.out.println(text.lastIndexOf("a "));
System.out.println(text.lastIndexOf('a', 20));
System.out.println(text.lastIndexOf("a ", 20));
System.out.println(text.lastIndexOf('z'));
}

////////////////////////////////////////////////////////
/* 문자열의 일부 값을 잘라내는 메소드 : substring */
public void substringCheck1() {
String text = "Java technology";
String technology = text.substring(5);
System.out.println(technology);
String tech = text.substring(5, 9);
System.out.println(tech);
}

////////////////////////////////////////////////////////
/* 문자열을 여러개의 String배열로 나누는 split 메소드 */
public void splitCheck() {
String text = "Java technology is both a programming language and a platform.";
String[] splitArray=text.split(" ");
for(String temp:splitArray) {
System.out.println(temp);
}
}
////////////////////////////////////////////////////////
/* 문자열을 합치는 메소드와 공백을 없애는 메소드 : trim */
public void trimCheck() {
String strings[] = new String[] {
" a", " b ", " c", "d ", "e f", " "
};
for(String string:strings) {
System.out.println("Before = ["+string+"] ");
System.out.println("After = Trim["+string.trim()+"] ");
}
}

////////////////////////////////////////////////////////
/* 내용을 교체하는 메소드 : replace */
public void replaceCheck() {
String text="The String class represents character strings.";
System.out.println(text.replace('s', 'z'));
System.out.println(text);
System.out.println(text.replace("tring", "trike"));
System.out.println(text.replaceAll(" ", "|"));
System.out.println(text.replaceFirst(" ", "|"));
}

////////////////////////////////////////////////////////
/* 특정 형식에 맞춰 값을 치환하는 메소드 : format */
public void formatCheck() {
String text = "'My name is %s." + "I'm %d years old, and I'm %f cm.";
String realText = String.format(text, "Choi jinwoo", 26, 178.5);
System.out.println(realText);
}

////////////////////////////////////////////////////////

/* immutable(변경 불가능한)한 String의 단점을 보완하는 클래스에는 StringBuffer와 StringBuilder 가 있습니다.
* StringBuffer : Thread safe 함.
* StringBuilder : Thread safe 하지 않음.
* 속도는 StringBuilder가 더 빠름.
*
* (String, StringBuilder, StringBuffer 클래스의 공통점)
* 모두 문자열을 다룬다, CharSequence 인터페이스를 구현했다.
*
* 일반적으로 하나의 메소드 내에서 문자열을 생성하여 더할 경우에는
* StringBuilder를 사용해도 전혀 상관 없다.
*
* 그러나, 어떤 클래스에 문자열을 생성하여 더하기위한 문자열을 처리하기 위한
* 인스턴스 변수가 선언되었고, 여러 쓰레드에서 이 변수를 동시에 접근하는 일이
* 있는 경우에는 반드시 StringBuffer를 사용해야만 한다.
*/
}



WRITTEN BY
SiriusJ

,