logo

Java의 문자열 배열

배열은 필수이자 가장 많이 사용되는 데이터 구조입니다. 자바 . 효율적이고 생산적인 특성으로 인해 프로그래머가 가장 많이 사용하는 데이터 구조 중 하나입니다. 배열은 유사한 데이터 유형 요소의 모음입니다. 요소를 저장하기 위해 연속적인 메모리 위치를 사용합니다.

문자열 배열은 고정된 수의 문자열 값으로 구성된 배열입니다. . 문자열은 일련의 문자입니다. 일반적으로 문자열은 불변 객체입니다. 즉, 문자열 값을 변경할 수 없습니다. 문자열 배열은 다른 데이터 유형의 배열과 유사하게 작동합니다.

~ 안에 정렬 , 고정된 요소 집합만 저장할 수 있습니다. 0부터 시작하는 인덱스 기반 데이터 구조입니다.위치. 첫 번째 요소는 인덱스 0에서 발생하고 2는nd요소는 인덱스 1에서 발생합니다.

주요 메소드 {Public static void main[ String [] args]; } Java에서는 문자열 배열이기도 합니다.

문자열 배열에 대해 다음 사항을 고려하십시오.

피트 데이비슨
  • 배열의 객체입니다.
  • 두 가지 방법으로 선언할 수 있습니다. 크기를 지정하거나 크기를 지정하지 않고.
  • 선언 시 또는 선언 후 값을 채워 초기화할 수 있습니다.
  • 요소를 선언한 후 문자열 배열에 추가할 수 있습니다.
  • 문자열 배열은 for 루프를 사용하여 반복할 수 있습니다.
  • 검색 및 정렬 작업은 문자열 배열에서 수행할 수 있습니다.

선언:

Array 선언에는 두 가지 유형이 있습니다. 즉, Array의 크기를 지정할 수 있거나 Array의 크기를 지정하지 않고 지정할 수 있습니다. 문자열 배열은 다음과 같이 선언할 수 있습니다.

 String[] stringArray1 //Declaration of the String Array without specifying the size String[] stringArray2 = new String[2]; //Declarartion by specifying the size 

배열을 선언하는 또 다른 방법은 다음과 같습니다. 문자열 strArray[] , 그러나 위에 지정된 방법이 더 효율적이며 권장됩니다.

초기화:

문자열 배열은 쉽게 초기화할 수 있습니다. 다음은 문자열 배열의 초기화입니다.

 1. String[] strAr1=new String[] {'Ani', 'Sam', 'Joe'}; //inline initialization 2. String[] strAr2 = {'Ani', 'Sam', ' Joe'}; 3. String[] strAr3= new String[3]; //Initialization after declaration with specific size strAr3[0]= 'Ani'; strAr3[1]= 'Sam'; strAr3[2]= 'Joe'; 

위의 세 가지 방법은 모두 String Array를 초기화하는 데 사용되며 동일한 값을 갖습니다.

3rd방법은 특정 크기 방법입니다. 여기서 인덱스 값은 (를 사용하여 찾을 수 있습니다. 배열 길이 - 1 ) 위 배열에서 인덱스 2보다 많은 요소에 액세스하려는 경우 수식을 사용합니다. 그것은 던질 것이다 Java.lang.ArrayIndexOutOfBoundsException 예외.

동작을 보여주기 위해 문자열 배열의 예를 살펴보겠습니다.

문자열 배열의 반복

SQL 연결

문자열 배열은 for 및 foreach 루프를 사용하여 반복할 수 있습니다. 아래 코드를 고려해보세요:

 String[] strAr = {&apos;Ani&apos;, &apos;Sam&apos;, &apos;Joe&apos;}; for (int i=0; i<strar.length; i++) { system.out.println(strar[i]); } for ( string str: strar) sytem.out.println(str); < pre> <h2>Adding Elements to a String Array</h2> <p>We can easily add the elements to the String Array just like other data types. It can be done using the following three methods:</p> <ul> <tr><td>Using Pre-Allocation of the Array</td>  </tr><tr><td>Using the Array List</td>  </tr><tr><td>By creating a new Array</td>  </tr></ul> <p>let&apos;s understand the above methods:</p> <h3>Using Pre-Allocation of the Array:</h3> <p>In this method, we already have an Array of larger size. For example, if we require to store the 10 elements, then we will create an Array of size 20. It is the easiest way to expand the Array elements.</p> <p>Consider the below example to add elements in a pre-allocated array.</p> <pre> // Java Program to add elements in a pre-allocated Array import java.util.Arrays; public class StringArrayDemo { public static void main(String[] args) { String[] sa = new String[7]; // Creating a new Array of Size 7 sa[0] = &apos;A&apos;; // Adding Array elements sa[1] = &apos;B&apos;; sa[2] = &apos;C&apos;; sa[3] = &apos;D&apos;; sa[4] = &apos;E&apos;; System.out.println(&apos;Original Array Elements:&apos; + Arrays.toString(sa)); int numberOfItems = 5; String newItem = &apos;F&apos;; // Expanding Array Elements Later String newItem2 =&apos;G&apos;; sa[numberOfItems++] = newItem; sa[numberOfItems++] = newItem2; System.out.println(&apos;Array after adding two elements:&apos; + Arrays.toString(sa)); } } </pre> <p> <strong>Output:</strong> </p> <pre> Original Array Elements:[A, B, C, D, E, null, null] Array after adding two elements:[A, B, C, D, E, F, G] </pre> <p>From the above example, we have added two elements in a pre-allocated Array.</p> <h3>Using ArrayList:</h3> <p>The <a href="/java-arraylist">ArrayList</a> is a fascinating data structure of the <a href="/collections-java">Java collection framework</a> . We can easily add elements to a <a href="/java-string">String</a> Array using an ArrayList as an intermediate data structure.</p> <p>Consider the below example to understand how to add elements to a String Array using ArrayList :</p> <pre> import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class StringArrayDemo1 { public static void main(String[] args) { // Defining a String Array String sa[] = { &apos;A&apos;, &apos;B&apos;, &apos;C&apos;, &apos;D&apos;, &apos;E&apos;, &apos;F&apos; }; // System.out.println(&apos;Initial Array:
&apos; + Arrays.toString(sa)); String ne = &apos;G&apos;; // Define new element to add Listl = new ArrayList( Arrays.asList(sa)); // Convert Array to ArrayList l.add(ne); // Add new element in ArrayList l sa = l.toArray(sa); // Revert Conversion from ArrayList to Array // printing the new Array System.out.println(&apos;Array with added Value: 
&apos; + Arrays.toString(sa)) ; } } </pre> <p> <strong>Output:</strong> </p> <pre> Initial Array: [A, B, C, D, E, F] Array with added value: [A, B, C, D, E, F, G] </pre> <h3>By Creating a New Array:</h3> <p>In this method, we will create a new Array with a larger size than the initial Array and accommodate the elements in it. We will copy all the elements to the newly added Array.</p> <p>Consider the below example:</p> <pre> // Java Program to add elements in a String Array by creating a new Array import java.util.Arrays; public class StringArrayDemo2 { public static void main(String[] args) { //Declaring Initial Array String[] sa = {&apos;A&apos;, &apos;B&apos;, &apos;C&apos; }; // Printing the Original Array System.out.println(&apos;Initial Array: &apos; + Arrays.toString(sa)); int length_Var = sa.length; //Defining the array length variable String newElement = &apos;D&apos;; // Defining new element to add //define new array with extended length String[] newArray = new String[ length_Var + 1 ]; //Adding all the elements to initial Array for (int i=0; i <sa.length; i++) { newarray[i]="sa" [i]; } specifying the position of added elements ( last) newarray[newarray.length- 1]="newElement;" make it original and print sa="newArray;" system.out.println('updated array: ' + arrays.tostring(sa)); < pre> <p> <strong>Output:</strong> </p> <pre> Initial Array: [A, B, C] updated Array: [A, B, C, D] </pre> <p>This is how we can add elements to a String Array. Let&apos;s understand how to search and sort elements in String Array.</p> <h2>Searching in String Array</h2> <p>For searching a String from the String Array, for loop is used. Consider the below example:</p> <pre> public class StringArrayExample { public static void main(String[] args) { String[] strArray = { &apos;Ani&apos;, &apos;Sam&apos;, &apos;Joe&apos; }; boolean x = false; //initializing x to false int in = 0; //declaration of index variable String s = &apos;Sam&apos;; // String to be searched // Iteration of the String Array for (int i = 0; i <strarray.length; i++) { if(s.equals(strarray[i])) in="i;" x="true;" break; } if(x) system.out.println(s +' string is found at index '+in); else not the array'); < pre> <p> <strong>Output:</strong> </p> <pre> Sam String is found at index 1 </pre> <p>In the above example, we have initialized a boolean variable <strong>x</strong> to false and an index variable to iterate through the string. Also, we have declared a local variable String variable <strong>s</strong> to be searched. Here, the break keyword will exit the loop as soon as the string is found.</p> <h2>Sorting in String Array</h2> <p>The sorting in the String array is quite easy. It is performed like in a traditional array. We use a sort() method to sort the Array elements. Sorting is easier than searching.</p> <p>Consider the below example to <a href="/how-sort-string-array-java">sort a String Array</a> :</p> <pre> //Java Program to sort elements in a String Array import java.util.Arrays; public class StringArraySorting { public static void main(String[] args) { // Adding String values String[] colors = {&apos;Cricket&apos;,&apos;Basketball&apos;,&apos;Football&apos;,&apos;Badminton&apos;,&apos;Tennis&apos;}; // Print Original values System.out.println(&apos;Entered Sports: &apos;+Arrays.toString(colors)); Arrays.sort(colors); // Sorting Elements // Print Sorted Values System.out.println(&apos;Sorted Sports: &apos;+Arrays.toString(colors)); } } </pre> <p> <strong>Output:</strong> </p> <pre> Entered Sports: [Cricket, Basketball, Football, Badminton, Tennis] Sorted Sports: [Badminton, Basketball, Cricket, Football, Tennis] </pre> <p>From the above example, we can see the elements from a String Array is sorted using the sort() method.</p> <p>We can also convert String Array to other data structures such as List, int Array, ArrayList, and more and vice-versa.</p> <hr></strarray.length;></pre></sa.length;></pre></strar.length;>

산출:

 Original Array Elements:[A, B, C, D, E, null, null] Array after adding two elements:[A, B, C, D, E, F, G] 

위의 예에서 사전 할당된 배열에 두 개의 요소를 추가했습니다.

ArrayList 사용:

그만큼 배열목록 의 흥미로운 데이터 구조입니다. Java 컬렉션 프레임워크 . 우리는 쉽게 요소를 추가할 수 있습니다. ArrayList를 중간 데이터 구조로 사용하는 배열입니다.

ArrayList를 사용하여 문자열 배열에 요소를 추가하는 방법을 이해하려면 아래 예제를 고려하십시오.

 import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class StringArrayDemo1 { public static void main(String[] args) { // Defining a String Array String sa[] = { &apos;A&apos;, &apos;B&apos;, &apos;C&apos;, &apos;D&apos;, &apos;E&apos;, &apos;F&apos; }; // System.out.println(&apos;Initial Array:
&apos; + Arrays.toString(sa)); String ne = &apos;G&apos;; // Define new element to add Listl = new ArrayList( Arrays.asList(sa)); // Convert Array to ArrayList l.add(ne); // Add new element in ArrayList l sa = l.toArray(sa); // Revert Conversion from ArrayList to Array // printing the new Array System.out.println(&apos;Array with added Value: 
&apos; + Arrays.toString(sa)) ; } } 

산출:

 Initial Array: [A, B, C, D, E, F] Array with added value: [A, B, C, D, E, F, G] 

새 어레이 생성:

이 방법에서는 초기 Array보다 더 큰 크기의 새 Array를 만들고 그 안에 요소를 수용합니다. 새로 추가된 배열에 모든 요소를 ​​복사하겠습니다.

아래 예를 고려하십시오.

배우 라쿨 프리트 싱
 // Java Program to add elements in a String Array by creating a new Array import java.util.Arrays; public class StringArrayDemo2 { public static void main(String[] args) { //Declaring Initial Array String[] sa = {&apos;A&apos;, &apos;B&apos;, &apos;C&apos; }; // Printing the Original Array System.out.println(&apos;Initial Array: &apos; + Arrays.toString(sa)); int length_Var = sa.length; //Defining the array length variable String newElement = &apos;D&apos;; // Defining new element to add //define new array with extended length String[] newArray = new String[ length_Var + 1 ]; //Adding all the elements to initial Array for (int i=0; i <sa.length; i++) { newarray[i]="sa" [i]; } specifying the position of added elements ( last) newarray[newarray.length- 1]="newElement;" make it original and print sa="newArray;" system.out.println(\'updated array: \' + arrays.tostring(sa)); < pre> <p> <strong>Output:</strong> </p> <pre> Initial Array: [A, B, C] updated Array: [A, B, C, D] </pre> <p>This is how we can add elements to a String Array. Let&apos;s understand how to search and sort elements in String Array.</p> <h2>Searching in String Array</h2> <p>For searching a String from the String Array, for loop is used. Consider the below example:</p> <pre> public class StringArrayExample { public static void main(String[] args) { String[] strArray = { &apos;Ani&apos;, &apos;Sam&apos;, &apos;Joe&apos; }; boolean x = false; //initializing x to false int in = 0; //declaration of index variable String s = &apos;Sam&apos;; // String to be searched // Iteration of the String Array for (int i = 0; i <strarray.length; i++) { if(s.equals(strarray[i])) in="i;" x="true;" break; } if(x) system.out.println(s +\' string is found at index \'+in); else not the array\'); < pre> <p> <strong>Output:</strong> </p> <pre> Sam String is found at index 1 </pre> <p>In the above example, we have initialized a boolean variable <strong>x</strong> to false and an index variable to iterate through the string. Also, we have declared a local variable String variable <strong>s</strong> to be searched. Here, the break keyword will exit the loop as soon as the string is found.</p> <h2>Sorting in String Array</h2> <p>The sorting in the String array is quite easy. It is performed like in a traditional array. We use a sort() method to sort the Array elements. Sorting is easier than searching.</p> <p>Consider the below example to <a href="/how-sort-string-array-java">sort a String Array</a> :</p> <pre> //Java Program to sort elements in a String Array import java.util.Arrays; public class StringArraySorting { public static void main(String[] args) { // Adding String values String[] colors = {&apos;Cricket&apos;,&apos;Basketball&apos;,&apos;Football&apos;,&apos;Badminton&apos;,&apos;Tennis&apos;}; // Print Original values System.out.println(&apos;Entered Sports: &apos;+Arrays.toString(colors)); Arrays.sort(colors); // Sorting Elements // Print Sorted Values System.out.println(&apos;Sorted Sports: &apos;+Arrays.toString(colors)); } } </pre> <p> <strong>Output:</strong> </p> <pre> Entered Sports: [Cricket, Basketball, Football, Badminton, Tennis] Sorted Sports: [Badminton, Basketball, Cricket, Football, Tennis] </pre> <p>From the above example, we can see the elements from a String Array is sorted using the sort() method.</p> <p>We can also convert String Array to other data structures such as List, int Array, ArrayList, and more and vice-versa.</p> <hr></strarray.length;></pre></sa.length;>

이것이 문자열 배열에 요소를 추가하는 방법입니다. 문자열 배열의 요소를 검색하고 정렬하는 방법을 알아봅시다.

문자열 배열에서 검색하기

문자열 배열에서 문자열을 검색하려면 for 루프가 사용됩니다. 아래 예를 고려하십시오.

 public class StringArrayExample { public static void main(String[] args) { String[] strArray = { &apos;Ani&apos;, &apos;Sam&apos;, &apos;Joe&apos; }; boolean x = false; //initializing x to false int in = 0; //declaration of index variable String s = &apos;Sam&apos;; // String to be searched // Iteration of the String Array for (int i = 0; i <strarray.length; i++) { if(s.equals(strarray[i])) in="i;" x="true;" break; } if(x) system.out.println(s +\' string is found at index \'+in); else not the array\'); < pre> <p> <strong>Output:</strong> </p> <pre> Sam String is found at index 1 </pre> <p>In the above example, we have initialized a boolean variable <strong>x</strong> to false and an index variable to iterate through the string. Also, we have declared a local variable String variable <strong>s</strong> to be searched. Here, the break keyword will exit the loop as soon as the string is found.</p> <h2>Sorting in String Array</h2> <p>The sorting in the String array is quite easy. It is performed like in a traditional array. We use a sort() method to sort the Array elements. Sorting is easier than searching.</p> <p>Consider the below example to <a href="/how-sort-string-array-java">sort a String Array</a> :</p> <pre> //Java Program to sort elements in a String Array import java.util.Arrays; public class StringArraySorting { public static void main(String[] args) { // Adding String values String[] colors = {&apos;Cricket&apos;,&apos;Basketball&apos;,&apos;Football&apos;,&apos;Badminton&apos;,&apos;Tennis&apos;}; // Print Original values System.out.println(&apos;Entered Sports: &apos;+Arrays.toString(colors)); Arrays.sort(colors); // Sorting Elements // Print Sorted Values System.out.println(&apos;Sorted Sports: &apos;+Arrays.toString(colors)); } } </pre> <p> <strong>Output:</strong> </p> <pre> Entered Sports: [Cricket, Basketball, Football, Badminton, Tennis] Sorted Sports: [Badminton, Basketball, Cricket, Football, Tennis] </pre> <p>From the above example, we can see the elements from a String Array is sorted using the sort() method.</p> <p>We can also convert String Array to other data structures such as List, int Array, ArrayList, and more and vice-versa.</p> <hr></strarray.length;>

위의 예에서는 부울 변수를 초기화했습니다. 엑스 false로 설정하고 인덱스 변수를 사용하여 문자열을 반복합니다. 또한 지역 변수 String 변수를 선언했습니다. 에스 검색됩니다. 여기서 break 키워드는 문자열이 발견되자마자 루프를 종료합니다.

문자열 배열로 정렬

String 배열의 정렬은 매우 쉽습니다. 이는 전통적인 배열처럼 수행됩니다. 배열 요소를 정렬하려면 sort() 메서드를 사용합니다. 검색보다 정렬이 더 쉽습니다.

MySQL 우분투 다시 시작

아래 예를 고려하여 문자열 배열 정렬 :

 //Java Program to sort elements in a String Array import java.util.Arrays; public class StringArraySorting { public static void main(String[] args) { // Adding String values String[] colors = {&apos;Cricket&apos;,&apos;Basketball&apos;,&apos;Football&apos;,&apos;Badminton&apos;,&apos;Tennis&apos;}; // Print Original values System.out.println(&apos;Entered Sports: &apos;+Arrays.toString(colors)); Arrays.sort(colors); // Sorting Elements // Print Sorted Values System.out.println(&apos;Sorted Sports: &apos;+Arrays.toString(colors)); } } 

산출:

 Entered Sports: [Cricket, Basketball, Football, Badminton, Tennis] Sorted Sports: [Badminton, Basketball, Cricket, Football, Tennis] 

위의 예에서 문자열 배열의 요소가 sort() 메서드를 사용하여 정렬되는 것을 볼 수 있습니다.

또한 문자열 배열을 List, int Array, ArrayList 등과 같은 다른 데이터 구조로 변환하거나 그 반대로 변환할 수도 있습니다.