String 이란?
String 활용
StringBuffer,StringBuilder
char data[] = {'a', 'b', 'c'};
String data1 ="abc";
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
String a ="Happy day";
String b ="a";
String c = "123";
char data[] = {'a', 'b', 'c'};
String i = new String(data);
String a = new String("Happy day");
String b = new String("a");
String c = new String("123");
+
연산자를 이용해서 문자열을 결합하는 경우 인스턴스내의 문자열이 바뀐느 것이 아니라 새로운 문자열이 담긴 String 인스턴스가 생성되는 것이다.String s=""
와 같은 문장이 있을때, 참조변수 s가 참조하고 있는 String 인스턴스는 내부에 new Char[0]
와 같이 길이가 0인 char형 배열을 저장하고 있는 것이다.String s=""
과 같은 표현이 가능하다고 해서 char c='';
와 같은 표현이 가능한 것은 아니다. char형 변수에는 반드시 하나의 문자를 지정해야 하낟.StringCompareEx
package me.whiteship.livestudy.string;
public class StringCompareEx {
public static void main(String[] args) {
String str ="Hello World";
String str1 = "hfllo World";
Object obj = str;
System.out.println(str.compareTo(str1));
System.out.println(str.compareToIgnoreCase(str1));
System.out.println(str.compareTo(obj.toString()));
}
}
output
-32
-1
0
equals
package me.whiteship.livestudy.string;
public class StringEqualsEx {
public static void main(String[] args) {
String s1= "hello";
String s2= "hello";
String s3= new String("hello");
String s4 = new String("Hello");
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));
}
}
output
true
true
false
package me.whiteship.livestudy.string;
public class StringEqualsEx {
public static void main(String[] args) {
String s1= "hello";
String s2= "hello";
String s3= new String("hello");
String s4 = new String("Hello");
System.out.println(s1==s2);
System.out.println(s1==s2);
System.out.println(s1==s4);
}
}
output
true
true
false
package me.whiteship.livestudy.string;
public class SearchLastString {
public static void main(String[] args) {
String str = "Hello world, Hello hi, Hello hihihi";
int lastIndex = str.lastIndexOf("Hello");
if(lastIndex==-1){
System.out.println("Hello not found");
}else{
System.out.println(lastIndex);
System.out.println(str.charAt(lastIndex));
}
}
}
output
23
H
package me.whiteship.livestudy.string;
public class StringExample {
public static void main(String[] args) {
String str = "Hello World, Hello JAVA";
System.out.println(str);
System.out.println(str.charAt(6));
System.out.println(removeChatAt(str,6));
}
public static String removeChatAt(String s, int pos){
return s.substring(0,pos)+s.substring(pos+1);
}
}
output
Hello World, Hello JAVA
W
Hello orld, Hello JAVA
public class RemoveCharacter
{
public static void main(String[] args)
{
StringBuilder MyString = new StringBuilder("Hello World");
System.out.println("The string before removing character: " + MyString);
MyString = MyString.deleteCharAt(5);
System.out.println("The string after removing character: " + MyString);
}
}
output
The string before removing character: Hello World
The string after removing character: HelloWorld
package me.whiteship.livestudy.string;
public class StringExample {
public static void main(String[] args) {
String str = "Hello World, Hello JAVA";
System.out.println(str.replace("H","F"));
System.out.println(str.replaceFirst("Hello","bye"));
System.out.println(str.replaceAll("Hello","bye"));
}
}
output
Fello World, Fello JAVA
bye World, Hello JAVA
bye World, bye JAVA
package me.whiteship.livestudy.string;
public class StringExample {
public static void main(String[] args) {
String str = "Hello World, Hello JAVA";
String str1 = new StringBuffer(str).reverse().toString();
System.out.println(str);
System.out.println(str1);
}
}
output
Hello World, Hello JAVA
AVAJ olleH ,dlroW olleH
package me.whiteship.livestudy.string;
public class StringExample {
public static void main(String[] args) {
String str = "Hello World, Hello JAVA";
char[] str1 = str.toCharArray();
for (int i = str1.length-1; i >=0; i--) {
System.out.println(str1[i]);
}
}
}
output
AVAJ olleH ,dlroW olleH
package me.whiteship.livestudy.string;
public class StringExample {
public static void main(String[] args) {
String str = "Hello World, Hello JAVA";
int idx = str.indexOf("Hello");
if(idx==-1){
System.out.println("Hello not found");
}else{
System.out.println(idx);
System.out.println(str.charAt(idx));
}
}
}
output
0
H
package me.whiteship.livestudy.string;
public class StringExample {
public static void main(String[] args) {
String str = "Hello World, Hello JAVA";
System.out.println(str.contains("JAVA"));
}
}
output
true
package me.whiteship.livestudy.string;
public class StringExample {
public static void main(String[] args) {
String str = "Hello-World-Hello-JAVA";
String [] tmp;
String [] tmp1;
String delimeter="-";
tmp = str.split(delimeter);
for (int i = 0; i < tmp.length; i++) {
System.out.println(tmp[i]);
}
System.out.println();
str = "max.min.avg.sum";
delimeter="\\.";
tmp1=str.split(delimeter);
for (int i = 0; i < tmp1.length; i++) {
System.out.println(tmp1[i]);
}
}
}
output
Hello
World
Hello
JAVA
max
min
avg
sum
package me.whiteship.livestudy.string;
public class StringExample {
public static void main(String[] args) {
String str = "Hello-World-Hello-JAVA";
String str1 = str.toUpperCase();
System.out.println(str);
System.out.println(str1);
}
}
output
Hello-World-Hello-JAVA
HELLO-WORLD-HELLO-JAVA
package me.whiteship.livestudy.string;
public class StringExample {
public static void main(String[] args) {
String str = "Hello-World-Hello-JAVA";
String str1 = "Hel4o-World-Hello-PYTHON";
boolean match = str.regionMatches(str.indexOf("World"),str1,str1.indexOf("World"),3);
System.out.println(match);
match = str.regionMatches(str.indexOf("Hello"),str1,str1.indexOf("Hel4o"),3);
System.out.println(match);
match = str.regionMatches(str.indexOf("Hello"),str1,str1.indexOf("Hel4o"),4);
System.out.println(match);
}
}
output
true
true
false
package me.whiteship.livestudy.string;
public class StringExample {
public static void main(String[] args) {
//String str1 = "Hello-World-Hello-JAVA";
//String str2 = "Hello-World-Hello-JAVA";
long start = System.currentTimeMillis();
for (int i = 0; i < 50_000; i++) {
String str1 = "Hello-World-Hello-JAVA";
String str2 = "Hello-World-Hello-JAVA";
}
long end = System.currentTimeMillis();
System.out.println(end-start+" milli sec");
start = System.currentTimeMillis();
for (int i = 0; i < 50_000; i++) {
String str3 = new String("Hello-World-Hello-JAVA");
String str4 = new String ("Hello-World-Hello-JAVA");
}
end = System.currentTimeMillis();
System.out.println(end-start+" milli sec");
}
}
output
2 milli sec
8 milli sec
package me.whiteship.livestudy.string;
public class StringExample {
public static void main(String[] args) {
//String str1 = "Hello-World-Hello-JAVA";
//String str2 = "Hello-World-Hello-JAVA";
String[] strings = new String[50_000];
for (int i = 0; i < strings.length; i++) {
strings[i] = "s"+i;
}
long start = System.currentTimeMillis();
for (int i = 0; i < strings.length; i++) {
strings[i] = "hello";
}
long end = System.currentTimeMillis();
System.out.println(end-start + " ms");
start = System.currentTimeMillis();
for (int i = 0; i < strings.length; i++) {
strings[i] = new String("hello");
}
end = System.currentTimeMillis();
System.out.println(end-start + " ms");
start = System.currentTimeMillis();
for (int i = 0; i < strings.length; i++) {
strings[i] = new String("hello");
strings[i] = strings[i].intern();
}
end = System.currentTimeMillis();
System.out.println(end-start + " ms");
}
}
output
1 ms
4 ms
9 ms
package me.whiteship.livestudy.string;
import java.util.Locale;
public class StringExample {
public static void main(String[] args) {
String str1 = "Hello-World-Hello-JAVA";
String str2 = "Hello-World-Hello-JAVA";
double e =Math.E;
System.out.format("%f%n",e);
System.out.format(Locale.GERMANY, "%-10.4f%n%n",e);
}
}
output
2.718282
2,7183
package me.whiteship.livestudy.string;
import java.util.Locale;
public class StringExample {
public static void main(String[] args) {
String str1 = "Hello-World-Hello-JAVA";
String str2 = "Hello-World-Hello-JAVA";
System.out.println(str1+str2);
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(str1);
stringBuffer.append(str2);
System.out.println(stringBuffer);
}
}
output
Hello-World-Hello-JAVAHello-World-Hello-JAVA
Hello-World-Hello-JAVAHello-World-Hello-JAVA
package me.whiteship.livestudy.string;
public class StringExample {
public static void main(String[] args) {
String str1 = "Hello-World-Hello-JAVA";
String str2 = "Hello-World-Hello-JAVA";
System.out.println(str1.codePointAt(0));
}
}
output
72
String str = " h E L L O ";
System.out.println(str.trim());
output
h E L L O
package me.whiteship.livestudy.string;
public class StringExample {
public static void main(String[] args) {
String str1 = "Hello-World-Hello-JAVA123";
String str2 = "Hello-World-Hello-JAVA";
System.out.println(str1.concat(str2));
}
}
output
Hello-World-Hello-JAVA123Hello-World-Hello-JAVA
package me.whiteship.livestudy.string;
public class StringExample {
public static void main(String[] args) {
String str1 = "Hello-World-Hello-JAVA123";
String str2 = "Hello-World-Hello-JAVA";
System.out.println(str1.substring(0,5));
System.out.println(str1.substring(6));
}
}
output
Hello
World-Hello-JAVA123
byte[] str = "가".getBytes("UTF-8"); // 문자열을 UTF-8로 변환
String str = new String(str, "UTF-8"); // byte 배열을 문자열로 변환
int i = 10;
String s= String.valueOf(i);
System.out.println(s);
int i = 10;
String s = i+"";
System.out.println(s);
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
String s= "10";
int i = Integer.valueOf(s);
System.out.println(i);
public final class StringBuffer
extends AbstractStringBuilder
implements java.io.Serializable, CharSequence
{
private transient char[] toStringCache;
StringBuffer 클래스의 인스턴스를 생성할 때, 적절한 길이의 char형 배열이 생성되고 , 이 배열은 문자열을 저장하고 편집하기 위한 공간(buffer)로 사용된다.
StringBuffer 인스턴스를 생성할때는 생성자 StringBuffer(int length)를 사용해서 StringBuffer 인스턴스에 저장될 문자열의 길이를 고려하여 충분히 여유 있는 크기로 지정하는 것이 좋다.
StringBuffer 인스턴스를 생성할 때, 버퍼의 크기를 지정해 주지 않으면 16개의 문자를 저장할 수 있는 크기의 버퍼를 생성한다.
public StringBuffer(int length) {
value = new char[length];
shared = false;
}
public StringBuffer() {
this(16);
}
public StringBuffer(String str) {
this(str.length() + 16);
append(str);
}
StringBuffer 인스턴스로 문자열을 다루는 작업을 할때, 버퍼의 크기가 작업하려는 문자열의 길이보다 작을때는 내부적으로 버퍼의 크기를 증가시키는 작업이 수행된다.
배열의 길이는 변경될수없으므로 새로운 길이의 배열을 생성한후에 이전 배열의 값을 복사해야한다
StringBuffer sb = new StringBuffer("abc");
StringBuffer sb2 = new StringBuffer("abc");
System.out.println(sb == sb2); // false
System.out.println(sb.equals(sb2)); // false