logo

Java의 문자열 클래스

문자열은 일련의 문자입니다. Java에서 String의 객체는 불변입니다. 이는 상수를 의미하며 일단 생성되면 변경할 수 없습니다.

문자열 만들기

Java에서 문자열을 만드는 방법에는 두 가지가 있습니다.

1. 문자열 리터럴

String s = techcodeview.com;>

2. 사용 새로운 예어

String s = new String (techcodeview.com);>

Java의 문자열 생성자

1. 문자열(바이트[]바이트_arr)

디코딩하여 새로운 문자열을 구성합니다. 바이트 배열 . 디코딩을 위해 플랫폼의 기본 문자 집합을 사용합니다.



예:

byte[] b_arr = {71, 101, 101, 107, 115}; String s_byte =new String(b_arr); //Geeks>

2. 문자열(byte[] byte_arr, 문자셋 char_set)

디코딩하여 새로운 문자열을 구성합니다. 바이트 배열 . 그것은 char_set 디코딩을 위해.

예:

byte[] b_arr = {71, 101, 101, 107, 115}; Charset cs = Charset.defaultCharset(); String s_byte_char = new String(b_arr, cs); //Geeks>

3. 문자열(바이트[] byte_arr, 문자열 char_set_name)

디코딩하여 새로운 문자열을 구성합니다. 바이트 배열 . 그것은 char_set_name 디코딩을 위해. 위의 구성과 유사해 보이며 유사한 기능 앞에 나타나지만 다음과 같은 작업을 수행합니다. 문자열(char_set_name 포함) 위의 생성자가 사용하는 동안 매개변수로 CharSet.

예:

byte[] b_arr = {71, 101, 101, 107, 115}; String s = new String(b_arr, 'US-ASCII'); //Geeks>

4. 문자열(바이트[] byte_arr, int start_index, int 길이)

다음에서 새 문자열을 구성합니다. 바이트 배열 에 따라 start_index(시작 위치) 그리고 길이(시작 위치로부터의 문자 수).

예:

byte[] b_arr = {71, 101, 101, 107, 115}; String s = new String(b_arr, 1, 3); // eek>

5. 문자열(byte[] byte_arr, int start_index, int length, Charset char_set)

다음에서 새 문자열을 구성합니다. 바이트 배열 에 따라 start_index(시작 위치) 그리고 length(시작 위치부터의 문자 수) .용도 char_set 디코딩을 위해.

예:

이진 트리의 예
byte[] b_arr = {71, 101, 101, 107, 115}; Charset cs = Charset.defaultCharset(); String s = new String(b_arr, 1, 3, cs); // eek>

6. 문자열(바이트[] byte_arr, int start_index, int 길이, 문자열 char_set_name)

다음에서 새 문자열을 구성합니다. 바이트 배열 에 따라 start_index(시작 위치) 그리고 length(시작 위치부터의 문자 수) .용도 char_set_name 디코딩을 위해.

예:

byte[] b_arr = {71, 101, 101, 107, 115}; String s = new String(b_arr, 1, 4, 'US-ASCII'); // eeks>

7. 문자열(char[] char_arr)

주어진 문자열에서 새 문자열을 할당합니다. 문자 배열

예:

char char_arr[] = {'G', 'e', 'e', 'k', 's'}; String s = new String(char_arr); //Geeks>

8. 문자열(char[] char_array, int start_index, int count)

주어진 문자열에서 문자열을 할당합니다. 문자 배열 하지만 선택하세요 세다 의 문자 시작_색인 .

예:

char char_arr[] = {'G', 'e', 'e', 'k', 's'}; String s = new String(char_arr , 1, 3); //eek>

9. 문자열(int[] uni_code_points, int 오프셋, int 개수)

다음에서 문자열을 할당합니다. 유니코드_어레이 하지만 선택하세요 세다 의 문자 시작_색인 .

예:

int[] uni_code = {71, 101, 101, 107, 115}; String s = new String(uni_code, 1, 3); //eek>

10. 문자열(StringBuffer s_buffer)

문자열에서 새 문자열을 할당합니다. s_buffer

예:

자바의 일반성
StringBuffer s_buffer = new StringBuffer('Geeks'); String s = new String(s_buffer); //Geeks>

11. 문자열(StringBuilder s_builder)

문자열에서 새 문자열을 할당합니다. s_builder

예:

StringBuilder s_builder = new StringBuilder('Geeks'); String s = new String(s_builder); //Geeks>


Java의 문자열 메소드

1. 정수 길이()

문자열의 문자 수를 반환합니다.

'techcodeview.com'.length(); // returns 13>

2. Char charAt(int i)

i에 있는 문자를 반환합니다.색인.

'techcodeview.com'.charAt(3); // returns ‘k’>

삼. 문자열 하위 문자열(int i)

i에서 하위 문자열을 반환합니다.끝낼 인덱스 문자입니다.

'techcodeview.com'.substring(3); // returns ksforGeeks>

4. 문자열 하위 문자열(int i, int j)

i에서 j-1 인덱스까지의 하위 문자열을 반환합니다.

 'techcodeview.com'.substring(2, 5); // returns eks>

5. 문자열 연결( 문자열 str)

지정된 문자열을 이 문자열의 끝에 연결합니다.

 String s1 = Geeks;  String s2 = forGeeks;  String output = s1.concat(s2); // returns techcodeview.com>

6. int indexOf (문자열 s)

지정된 문자열이 처음 나타나는 문자열 내의 인덱스를 반환합니다.

입력 문자열에 String s가 없으면 -1이 기본값으로 반환됩니다.

1. String s = Learn Share Learn;  int output = s.indexOf(Share); // returns 6 2. String s = 'Learn Share Learn'  int output = s.indexOf(Play); // return -1>

7. int indexOf (문자열 s, int i)

지정된 인덱스에서 시작하여 지정된 문자열이 처음 나타나는 문자열 내의 인덱스를 반환합니다.

 String s = Learn Share Learn;  int output = s.indexOf('ea',3);// returns 13>

8. 정수 lastIndexOf(문자열 s)

지정된 문자열이 마지막으로 나타나는 문자열 내의 인덱스를 반환합니다.

데이터 프레임을 만드는 팬더

입력 문자열에 String s가 없으면 -1이 기본값으로 반환됩니다.

 1. String s = Learn Share Learn;  int output = s.lastIndexOf('a'); // returns 14 2. String s = 'Learn Share Learn'  int output = s.indexOf(Play); // return -1>

9. 부울 같음(객체 otherObj)

이 문자열을 지정된 개체와 비교합니다.

 Boolean out = Geeks.equals(Geeks); // returns true  Boolean out = Geeks.equals(geeks); // returns false>

10. 부울 =IgnoreCase(String anotherString)

대소문자 고려 사항을 무시하고 문자열을 다른 문자열과 비교합니다.

 Boolean out= Geeks.equalsIgnoreCase(Geeks); // returns true  Boolean out = Geeks.equalsIgnoreCase(geeks); // returns true>

11. int CompareTo(String anotherString)

두 문자열을 사전순으로 비교합니다.

 int out = s1.compareTo(s2);  // where s1 and s2 are // strings to be compared  This returns difference s1-s2. If :  out <0 // s1 comes before s2  out = 0 // s1 and s2 are equal.  out>0 // s1은 s2 뒤에 옵니다.>

12. int CompareToIgnoreCase(String anotherString)

대소문자 고려 사항을 무시하고 두 문자열을 사전순으로 비교합니다.

 int out = s1.compareToIgnoreCase(s2);  // where s1 and s2 are  // strings to be compared  This returns difference s1-s2. If :  out <0 // s1 comes before s2  out = 0 // s1 and s2 are equal.  out>0 // s1은 s2 뒤에 옵니다.>

메모: 이 경우 문자의 대소문자를 고려하지 않습니다(대문자인지 소문자인지 무시합니다).

13. 문자열 toLowerCase()

문자열의 모든 문자를 소문자로 변환합니다.

String word1 = HeLLo; String word3 = word1.toLowerCase(); // returns hello'>

14. 문자열 toUpperCase()

문자열의 모든 문자를 대문자로 변환합니다.

String word1 = HeLLo; String word2 = word1.toUpperCase(); // returns HELLO>

열 다섯. 문자열 다듬기()

양쪽 끝의 공백을 제거하여 문자열의 복사본을 반환합니다. 중간에 있는 공백에는 영향을 주지 않습니다.

String word1 = Learn Share Learn ; String word2 = word1.trim(); // returns Learn Share Learn>

16. 문자열 교체(char oldChar, char newChar)

모든 항목을 대체하여 새 문자열을 반환합니다. 오래된 문자 ~와 함께 newChar.

String s1 = feeksforfeeks; String s2 = feeksforfeeks.replace(‘f’ ,’g’); // return geeksforgeeks>

메모: s1은 여전히 ​​feeksforfeeks이고 s2는 geeksgorgeeks입니다.

17. 부울 포함(문자열) :

문자열에 주어진 문자열이 포함되어 있으면 true를 반환합니다.

String s1='geeksforgeeks'; String s2='geeks'; s1.contains(s2) // return true>

18. Char[] toCharArray():

이 문자열을 새 문자 배열로 변환합니다.

싱글턴 디자인 패턴 자바
String s1='geeksforgeeks'; char []ch=s1.toCharArray(); // returns [ 'g', 'e' , 'e' , 'k' , 's' , 'f', 'o', 'r' , 'g' , 'e' , 'e' , 'k' ,'s' ]>

19. 부울 별(문자열):

문자열이 이 접두사로 시작하면 true를 반환합니다.

String s1='geeksforgeeks'; String s2='geeks'; s1.startsWith(s2) // return true>

문자열 생성자 및 문자열 메서드의 예

다음은 위에서 언급한 주제의 구현입니다.

자바
// Java code to illustrate different constructors and methods // String class. import java.io.*; import java.util.*; // Driver Class class Test {  // main function  public static void main (String[] args)  {  String s= 'techcodeview.com';  // or String s= new String ('techcodeview.com');  // Returns the number of characters in the String.  System.out.println('String length = ' + s.length());  // Returns the character at ith index.  System.out.println('Character at 3rd position = '  + s.charAt(3));  // Return the substring from the ith index character  // to end of string  System.out.println('Substring ' + s.substring(3));  // Returns the substring from i to j-1 index.  System.out.println('Substring = ' + s.substring(2,5));  // Concatenates string2 to the end of string1.  String s1 = 'Geeks';  String s2 = 'forGeeks';  System.out.println('Concatenated string = ' +  s1.concat(s2));  // Returns the index within the string  // of the first occurrence of the specified string.  String s4 = 'Learn Share Learn';  System.out.println('Index of Share ' +  s4.indexOf('Share'));  // Returns the index within the string of the  // first occurrence of the specified string,  // starting at the specified index.  System.out.println('Index of a = ' +  s4.indexOf('a',3));  // Checking equality of Strings  Boolean out = 'Geeks'.equals('geeks');  System.out.println('Checking Equality ' + out);  out = 'Geeks'.equals('Geeks');  System.out.println('Checking Equality ' + out);  out = 'Geeks'.equalsIgnoreCase('gEeks ');  System.out.println('Checking Equality ' + out);  //If ASCII difference is zero then the two strings are similar  int out1 = s1.compareTo(s2);  System.out.println('the difference between ASCII value is='+out1);  // Converting cases  String word1 = 'GeeKyMe';  System.out.println('Changing to lower Case ' +  word1.toLowerCase());  // Converting cases  String word2 = 'GeekyME';  System.out.println('Changing to UPPER Case ' +  word2.toUpperCase());  // Trimming the word  String word4 = ' Learn Share Learn ';  System.out.println('Trim the word ' + word4.trim());  // Replacing characters  String str1 = 'feeksforfeeks';  System.out.println('Original String ' + str1);  String str2 = 'feeksforfeeks'.replace('f' ,'g') ;  System.out.println('Replaced f with g ->' + str2);  } }>

산출
String length = 13 Character at 3rd position = k Substring ksforGeeks Substring = eks Concatenated string = techcodeview.com Index of Share 6 Index of a = 8 Checking Equality false Checking Equality ...>

세트 – 2의 경우 다음을 참조할 수 있습니다. Java의 Java.lang.String 클래스 | 세트 2

이 기사는 기고자: Rahul Agrawal과 유용한 사용자.