logo

String Array i Java

Et array er en vigtig og mest brugt datastruktur i Java . Det er en af ​​de mest brugte datastrukturer af programmører på grund af dens effektive og produktive natur; Arrayet er en samling af lignende datatypeelementer. Den bruger en sammenhængende hukommelsesplacering til at gemme elementerne.

En String Array er en Array med et fast antal String-værdier . En streng er en sekvens af tegn. Generelt er en streng et uforanderligt objekt, hvilket betyder, at værdien af ​​strengen ikke kan ændres. String Array fungerer på samme måde som andre datatyper af Array.

I Array , kan kun et fast sæt elementer gemmes. Det er en indeksbaseret datastruktur, som starter fra 0thposition. Det første element vil finde sted i indeks 0, og 2ndelement vil finde sted i indeks 1, og så videre.

Hovedmetoden {Public static void main[ String [] args]; } i Java er også en String Array.

Overvej nedenstående punkter om String Array:

  • Det er et objekt i Arrayet.
  • Det kan erklæres ved de to metoder; ved at angive størrelsen eller uden at angive størrelsen.
  • Den kan initialiseres enten på deklarationstidspunktet eller ved at udfylde værdierne efter deklarationen.
  • Elementerne kan tilføjes til en String Array efter at have erklæret den.
  • String Array kan gentages ved hjælp af for-løkken.
  • Søge- og sorteringsoperationen kan udføres på String Array.

Erklæring:

Array-deklarationen er af to typer, enten kan vi angive størrelsen af ​​arrayet eller uden at specificere størrelsen af ​​arrayet. En String Array kan erklæres som følger:

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

En anden måde at erklære Array på er String strArray[] , men de ovenfor angivne metoder er mere effektive og anbefales.

Initialisering:

String Array kan nemt initialiseres. Nedenfor er initialiseringen af ​​String Array:

 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'; 

Alle de ovennævnte tre måder bruges til at initialisere String Array og har samme værdi.

Den 3rdmetode er en specifik størrelsesmetode. I denne kan værdien af ​​indekset findes ved hjælp af ( arraylængde - 1 ) formel, hvis vi ønsker at få adgang til elementerne mere end indekset 2 i ovenstående Array. Det vil kaste Java.lang.ArrayIndexOutOfBoundsException undtagelse.

Lad os se et eksempel på String Array for at demonstrere dets adfærd:

base64 afkode i js

Iteration af String Array

String Array kan gentages ved hjælp af for og foreach-løkken. Overvej nedenstående kode:

 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;>

Produktion:

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

Fra ovenstående eksempel har vi tilføjet to elementer i et præ-allokeret Array.

Brug af ArrayList:

Det ArrayList er en fascinerende datastruktur af Java-samlingsramme . Vi kan nemt tilføje elementer til en Snor Array ved hjælp af en ArrayList som en mellemliggende datastruktur.

Overvej nedenstående eksempel for at forstå, hvordan man tilføjer elementer til en String Array ved hjælp af ArrayList:

det dejligste smil i verden
 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)) ; } } 

Produktion:

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

Ved at oprette et nyt array:

I denne metode vil vi oprette et nyt Array med en større størrelse end det oprindelige Array og rumme elementerne i det. Vi kopierer alle elementerne til det nyligt tilføjede Array.

Overvej nedenstående eksempel:

 // 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;>

Sådan kan vi tilføje elementer til en String Array. Lad os forstå, hvordan man søger og sorterer elementer i String Array.

Søgning i String Array

Til søgning af en streng fra String Array bruges for loop. Overvej nedenstående eksempel:

 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;>

I ovenstående eksempel har vi initialiseret en boolesk variabel x til falsk og en indeksvariabel til at iterere gennem strengen. Vi har også erklæret en lokal variabel String-variabel s skal søges. Her vil søgeordet break forlade løkken, så snart strengen er fundet.

Sortering i String Array

Sorteringen i String-arrayet er ret let. Det udføres som i et traditionelt array. Vi bruger en sort()-metode til at sortere Array-elementerne. Sortering er nemmere end at søge.

Overvej nedenstående eksempel til sortere en String Array :

 //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)); } } 

Produktion:

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

Fra ovenstående eksempel kan vi se, at elementerne fra en String Array er sorteret ved hjælp af sort()-metoden.

Vi kan også konvertere String Array til andre datastrukturer såsom List, int Array, ArrayList og mere og omvendt.