홍강zone

[Java] 데이터와 연산,문자열에 대해서 escape, length, replace 본문

Java

[Java] 데이터와 연산,문자열에 대해서 escape, length, replace

홍강 2023. 4. 4. 03:14

Number=숫자

- 자바에서 숫자는 다른 기호와 함께 입력하지 않고 그대로 입력한다.

 

String=문자

- 문자열은 쌍따옴표"" 안에 적는다.

- +연산자는 결합의 연산을 수행한다.

- 문자열 간에는 * 연산자를 사용할 수 없다.

- length 연산은 문자열의 길이를 알려준.

public class Datatype {

	public static void main(String[] args) {
		System.out.println(6); // Number
		System.out.println("six"); // String
		
		System.out.println("6"); // String 6
		
		System.out.println(6+6); // 12
		System.out.println("6"+"6"); // 66
		
		System.out.println(6*6); // 36
//		System.out.println("6"*"6");

		System.out.println("1111".length()); // 4
//		System.out.println(1111.length());
	}

}

Math 클래스

- 사칙연산자 이외에도 수학과 관련된 것들을 모아놓은 클래스

 

System.out.println(Math.PI); // 파이를 나타내줌

System.out.println(Math.floor(Math.PI)); // 내림
System.out.println(Math.ceil(Math.PI)); //  올림

public class Number {

	public static void main(String[] args) {
		// 연산자 Operator
		System.out.println(6+2); // 8
		System.out.println(6-2); // 4
		System.out.println(6*2); // 12
		System.out.println(6/2); // 3
		
		System.out.println(Math.PI); // 3.141592653589793
		System.out.println(Math.floor(Math.PI)); // 3.0 내림
		System.out.println(Math.ceil(Math.PI)); // 4.0 올림
	}

}

문자(Character)

오직 한 개의 문자만 포함될 수 있으며 따옴표 (' ')로 작성한다.

System.out.println('H');

 

문자열(String)

- 문자의 나열이다. 큰따옴표 (" ")로 작성한다.

System.out.println("Hello World");

 

이스케이프(escape) 기호 (역슬래시 \)

문자열에서 줄바꿈을 하고 싶다면 역슬래시n (\n)을 줄을 바꾸고 싶은 위치에 삽입한다.

System.out.println("Hello \nWorld");

 

쌍따옴표를 문자열에 입력하고자 할 때에는 쌍따옴표 앞에 역슬래시를 삽입한다.

System.out.println("Hello \"World\""); 

결과=Hello "World"

역슬래시가 World밖의 쌍따옴표를 특수한 문자가 아닌 일반 문자라고 나타내 주는 역할을 한다.

 

public class StringApp {

	public static void main(String[] args) {
		
		System.out.println("Hello World"); // String(문자열)
//		System.out.println('Hello World'); // 에러 작은따옴표는 Character를 나타냄 한 글자만 표현가능
		System.out.println('H'); // Character(문자)
		System.out.println("H"); // String(문자열)
		
		
		// new line
		System.out.println("Hello \nWorld"); // 줄바꿈
		// escape
		System.out.println("Hello \"World\""); // Hello "World"

	}

}

.length() 는 문자열의 길이를 산출한다.

System.out.println("Hello World".length());

결과 = 11

 

.replace(" " , " ") 는 기존의 문자열에서 바꾸고 싶은 부분을 먼저 입력하고, 바꾸고자 하는 문자열을 입력해준다.

System.out.println("Hello, kang ... bye.".replace("kang", "jeong"));

결과 = Hello, jeong ... bye.

public class StringOperation {

	public static void main(String[] args) {
		
		System.out.println("Hello World".length());
		System.out.println("Hello, kang ... bye.".replace("kang", "jeong"));

	}

}