> Java > java지도 시간 > 본문

Java 문자열 연산자

PHPz
풀어 주다: 2024-08-30 15:20:11
원래의
491명이 탐색했습니다.

다음 문서인 Java 문자열 연산자에서는 Java 문자열에 사용되는 연산자와 메서드에 대한 개요를 제공합니다. 문자열은 일반적으로 리터럴 상수 또는 일종의 변수로서의 문자 시퀀스입니다. Java에서 문자열은 객체로 처리되며 Java 플랫폼은 이러한 문자열을 생성하고 조작할 수 있는 String 클래스를 제공합니다. Java String은 가장 널리 사용되는 클래스 중 하나이며 java.lang 패키지에 정의되어 있습니다. 연산자는 일반적으로 컴파일러에게 특정 수학적 또는 논리적 조작을 수행하도록 요청하는 기호입니다. 입력을 피연산자로 취하고 일부 값을 출력으로 반환합니다. Java의 연산자는 작업을 수행하는 데 사용되는 기호와도 같습니다. 예: +, -, *, / 등

광고 이 카테고리에서 인기 있는 강좌 JAVA MASTERY - 전문 분야 | 78 코스 시리즈 | 15가지 모의고사

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

Java 문자열 연산

문자열은 "Hello, world!"와 같이 큰따옴표로 묶인 텍스트 형식의 문자열 리터럴과 연결됩니다. 따라서 String 인스턴스를 생성하기 위해 생성자를 호출하는 대신 문자열을 String 변수에 직접 할당할 수 있습니다.

Java에서 String은 연산자 오버로딩이 허용되는 유일한 클래스입니다. 예를 들어 + 연산자를 사용하여 두 문자열을 연결할 수 있습니다.

예:

"a"+"b"=" ab"
로그인 후 복사

Java 문자열 객체를 생성하는 두 가지 방법:-

1. 문자열 리터럴 사용: Java 문자열 리터럴은 큰따옴표를 사용하여 만들 수 있습니다. 예:

String s="Hello";
로그인 후 복사

2. 새 키워드 사용: "new" 키워드를 사용하여 Java 문자열을 생성할 수도 있습니다. 예:

String s=new String("Hello");
로그인 후 복사

Java 문자열 클래스는 직렬화 가능, 비교 가능 및 CharSequence의 세 가지 인터페이스를 구현합니다. Java 문자열은 불변이고 고정되어 있으므로 문자열 조작이 필요할 때마다 새 문자열을 생성해야 합니다. 그리고 문자열 조작은 리소스를 소비하므로 Java는 StringBuffer와 StringBuilder라는 두 가지 유틸리티 클래스를 제공합니다. 이 두 유틸리티 클래스를 사용하면 Java 문자열을 조작하는 것이 더 쉬워집니다. 몇 가지 예를 살펴보겠습니다.

문자열 클래스의 메서드

String 클래스의 메소드를 살펴보겠습니다.

1. 문자열 길이

Java 문자열은 기본적으로 문자열에 대해 일부 작업을 수행하는 메서드를 갖는 객체입니다. 예를 들어, "length()" 메소드를 사용하면 문자열의 길이를 찾을 수 있습니다. :

public class MyClass
public static void main(String[] args) {
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int len = txt.length();
System.out.println("The length of the txt string is: " + len);
}
}
로그인 후 복사

출력:

Java 문자열 연산자

2. 대문자 & 소문자

문자열을 대문자와 소문자로 만드는 문자열 메서드는 다음과 같습니다: toUpperCase() 및 toLowerCase()

예:

public class MyClass {
public static void main(String[] args) {
String txt = "Hello World";
System.out.println(txt.toUpperCase());
System.out.println(txt.toLowerCase());
}
}
로그인 후 복사

출력:

Java 문자열 연산자

3. 주어진 문자열에서 인덱스 찾기

"indexOf()" 메소드를 사용하여 Java에서 특정 문자열의 인덱스를 찾을 수 있습니다. 공백도 포함된 특정 텍스트가 처음으로 나타나는 인덱스 위치를 반환합니다.

코드:

public class MyClass {
public static void main(String[] args) {
String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate"));
}
}
로그인 후 복사

출력:

Java 문자열 연산자

주의: Java에서는 계산 위치가 0부터 시작되는 것으로 간주됩니다. 이는 "0"이 주어진 문자열에서 첫 번째 위치이고 "1"이 두 번째 위치로 간주되고 "2"가 세 번째번째 위치로 간주되어 곧 진행된다는 의미입니다.

4. Java 문자열 연결

숫자 추가(Java 문자열 연결에서)에 사용되는 "함께"를 의미하는 연산자 "+"를 고려하면 Java에서 문자열을 추가하는 데 동일한 연산자를 사용하여 문자열을 생성할 수 있습니다. 새로운 문자열. 그리고 이 작업을 문자열 연결이라고 합니다.

예시 #1

코드:

public class MyClass {
public static void main(String[] args) {
String firstName = "Raju";
String lastName = "Raj";
System.out.println(firstName + " " + lastName);
}
}
로그인 후 복사

출력:

Java 문자열 연산자

참고: 인쇄 시 firstName과 lastName 사이에 공백을 만들기 위해 빈 텍스트(“”)를 추가했습니다.

concat() 메소드를 사용하여 두 문자열을 연결할 수도 있습니다.

예시 #2

코드:

public class MyClass {
public static void main(String[] args) {
String firstName = "Raju ";
String lastName = "Raj";
System.out.println(firstName.concat(lastName));
}
}
로그인 후 복사

출력:

Java 문자열 연산자

5. 문자열 다듬기

시작과 끝 부분에 공백이 있는 문자열이 있는 경우 이 방법을 사용하면 공백을 제거하는 데 도움이 됩니다.

Example:

Code:

class StringTrim{
public static void main(String args[]){
String s1 = new String(" AbodeQA ");
s1 = s1.trim();
System.out.println(s1);
}
}
로그인 후 복사

Output:

Java 문자열 연산자

Java String Class Methods

The java.lang.string class provides many useful methods to perform operations.

Below are some of the methods which are supported by the String class:

Method

Description

char charAt(int index) Returns char value for the index
String concat(String str) It concatenates the string to the end
boolean equals(Object another) Checks the equality of string with the given
int compareTo(Object o) Compares the string to other objects
static String format(String format, Object… args) It returns a string that is formatted
boolean endsWith(String suffix) For testing the string if it ends with suffix or not
byte getBytes() Encodes a string to a sequence of bytes
int indexOf(int ch) Returns the char value index
boolean isEmpty() It checks if the string is empty or not
int lastIndexOf(String regex) Returns index of the rightmost occurrence
String intern() It returns interned string
int length() Returns length of the sting
int hashCode() It returns the hash code
boolean matches(String regex) Checks if a string matches the regular expression
String trim() It removes the starting & ending spaces of the string
String[] split(String regex) It returns a split string to matching a regex
String toLowerCase() Returns string to lowercase
String substring(int beginIndex) It returns the substring for the starting index
String toUpperCase() Returns string to uppercase
String replace(char old, char new) It replaces the occurrences of the char value

위 내용은 Java 문자열 연산자의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!