El Classe Java String charAt() retorna el mètode un valor de caràcter al número d'índex donat .
El número d'índex comença des de 0 i va a n-1, on n és la longitud de la cadena. Torna StringIndexOutOfBoundsException, si el número d'índex donat és superior o igual a la longitud d'aquesta cadena o un nombre negatiu.
Sintaxi
public char charAt(int index)
El mètode accepta índex com a paràmetre. L'índex inicial és 0. Retorna un caràcter en una posició d'índex específica d'una cadena. Es tira StringIndexOutOfBoundsException si l'índex és un valor negatiu o superior a aquesta longitud de cadena.
Especificat per
CharSequence interfície, situada dins del paquet java.lang.
Implementació interna
public char charAt(int index) { if ((index = value.length)) { throw new StringIndexOutOfBoundsException(index); } return value[index]; }
Java String charAt() Exemples de mètodes
Vegem el programa Java relacionat amb la cadena en què utilitzarem el mètode charAt() que realitza alguna operació sobre la cadena de dades.
Nom de l'arxiu: CharAtExample.java
public class CharAtExample{ public static void main(String args[]){ String name='javatpoint'; char ch=name.charAt(4);//returns the char value at the 4th index System.out.println(ch); }}Prova-ho ara
Sortida:
t
Vegem l'exemple del mètode charAt() on estem passant un valor d'índex més gran. En aquest cas, llança StringIndexOutOfBoundsException en temps d'execució.
Nom de l'arxiu: CharAtExample.java
public class CharAtExample{ public static void main(String args[]){ String name='javatpoint'; char ch=name.charAt(10);//returns the char value at the 10th index System.out.println(ch); }}
Sortida:
Exception in thread 'main' java.lang.StringIndexOutOfBoundsException: String index out of range: 10 at java.lang.String.charAt(String.java:658) at CharAtExample.main(CharAtExample.java:4)
Accés al primer i al darrer caràcter mitjançant el mètode charAt().
Vegem un exemple senzill on estem accedint al primer i a l'últim caràcter de la cadena proporcionada.
Nom de l'arxiu: CharAtExample3.java
public class CharAtExample3 { public static void main(String[] args) { String str = 'Welcome to Javatpoint portal'; int strLength = str.length(); // Fetching first character System.out.println('Character at 0 index is: '+ str.charAt(0)); // The last Character is present at the string length-1 index System.out.println('Character at last index is: '+ str.charAt(strLength-1)); } }
Sortida:
Character at 0 index is: W Character at last index is: l
Imprimeix els caràcters presentats en posicions estranyes mitjançant el mètode charAt().
Vegem un exemple on estem accedint a tots els elements presents a un índex imparell.
Nom de l'arxiu: CharAtExample4.java
public class CharAtExample4 { public static void main(String[] args) { String str = 'Welcome to Javatpoint portal'; for (int i=0; i<=str.length()-1; i++) { if(i%2!="0)" system.out.println('char at '+i+' place '+str.charat(i)); } < pre> <p> <strong>Output:</strong> </p> <pre> Char at 1 place e Char at 3 place c Char at 5 place m Char at 7 place Char at 9 place o Char at 11 place J Char at 13 place v Char at 15 place t Char at 17 place o Char at 19 place n Char at 21 place Char at 23 place o Char at 25 place t Char at 27 place l </pre> <p>The position such as 7 and 21 denotes the space.</p> <h3>Counting Frequency of a character in a String by Using the charAt() Method</h3> <p>Let's see an example in which we are counting frequency of a character in the given string.</p> <p> <strong>FileName:</strong> CharAtExample5.java</p> <pre> public class CharAtExample5 { public static void main(String[] args) { String str = 'Welcome to Javatpoint portal'; int count = 0; for (int i=0; i<=str.length()-1; i++) { if(str.charat(i)="=" 't') count++; } system.out.println('frequency of t is: '+count); < pre> <p> <strong>Output:</strong> </p> <pre> Frequency of t is: 4 </pre> <h3>Counting the Number of Vowels in a String by Using the chatAt() Method</h3> <p>Let's see an example where we are counting the number of vowels present in a string with the help of the charAt() method.</p> <p> <strong>FileName:</strong> CharAtExample6.java</p> <pre> // import statement import java.util.*; public class CharAtExample6 { ArrayList al; // constructor for creating and // assigning values to the ArrayList al CharAtExample6() { al = new ArrayList(); al.add('A'); al.add('E'); al.add('a'); al.add('e'); al.add('I'); al.add('O'); al.add('i'); al.add('o'); al.add('U'); al.add('u'); } // a method that checks whether the character c is a vowel or not private boolean isVowel(char c) { for(int i = 0; i <al.size(); 1 i++) { if(c="=" al.get(i)) return true; } false; a method that calculates vowels in the string s public int countvowels(string s) countvowel="0;" store total number of size="s.length();" for(int j="0;" < size; j++) char c="s.charAt(j);" if(isvowel(c)) vowel found! increase count by + 1; countvowel; main static void main(string argvs[]) creating an object class charatexample6 obj="new" charatexample6(); str="Javatpoint is a great site for learning Java." ; noofvowel="obj.countVowels(str);" system.out.println('string: ' str); system.out.println('total are: '+ ' '); noofvowel); pre> <p> <strong>Output:</strong> </p> <pre> String: Javatpoint is a great site for learning Java. Total number of vowels in the string are: 16 String: One apple in a day keeps doctor away. Total number of vowels in the string are: 13 </pre> <hr></al.size();></pre></=str.length()-1;></pre></=str.length()-1;>
La posició com ara 7 i 21 denota l'espai.
Recompte de la freqüència d'un caràcter en una cadena mitjançant el mètode charAt().
Vegem un exemple en què estem comptant la freqüència d'un caràcter a la cadena donada.
Nom de l'arxiu: CharAtExample5.java
public class CharAtExample5 { public static void main(String[] args) { String str = 'Welcome to Javatpoint portal'; int count = 0; for (int i=0; i<=str.length()-1; i++) { if(str.charat(i)="=" \'t\') count++; } system.out.println(\'frequency of t is: \'+count); < pre> <p> <strong>Output:</strong> </p> <pre> Frequency of t is: 4 </pre> <h3>Counting the Number of Vowels in a String by Using the chatAt() Method</h3> <p>Let's see an example where we are counting the number of vowels present in a string with the help of the charAt() method.</p> <p> <strong>FileName:</strong> CharAtExample6.java</p> <pre> // import statement import java.util.*; public class CharAtExample6 { ArrayList al; // constructor for creating and // assigning values to the ArrayList al CharAtExample6() { al = new ArrayList(); al.add('A'); al.add('E'); al.add('a'); al.add('e'); al.add('I'); al.add('O'); al.add('i'); al.add('o'); al.add('U'); al.add('u'); } // a method that checks whether the character c is a vowel or not private boolean isVowel(char c) { for(int i = 0; i <al.size(); 1 i++) { if(c="=" al.get(i)) return true; } false; a method that calculates vowels in the string s public int countvowels(string s) countvowel="0;" store total number of size="s.length();" for(int j="0;" < size; j++) char c="s.charAt(j);" if(isvowel(c)) vowel found! increase count by + 1; countvowel; main static void main(string argvs[]) creating an object class charatexample6 obj="new" charatexample6(); str="Javatpoint is a great site for learning Java." ; noofvowel="obj.countVowels(str);" system.out.println(\'string: \' str); system.out.println(\'total are: \'+ \' \'); noofvowel); pre> <p> <strong>Output:</strong> </p> <pre> String: Javatpoint is a great site for learning Java. Total number of vowels in the string are: 16 String: One apple in a day keeps doctor away. Total number of vowels in the string are: 13 </pre> <hr></al.size();></pre></=str.length()-1;>
Comptar el nombre de vocals d'una cadena utilitzant el mètode chatAt().
Vegem un exemple on estem comptant el nombre de vocals presents en una cadena amb l'ajuda del mètode charAt().
Nom de l'arxiu: CharAtExample6.java
// import statement import java.util.*; public class CharAtExample6 { ArrayList al; // constructor for creating and // assigning values to the ArrayList al CharAtExample6() { al = new ArrayList(); al.add('A'); al.add('E'); al.add('a'); al.add('e'); al.add('I'); al.add('O'); al.add('i'); al.add('o'); al.add('U'); al.add('u'); } // a method that checks whether the character c is a vowel or not private boolean isVowel(char c) { for(int i = 0; i <al.size(); 1 i++) { if(c="=" al.get(i)) return true; } false; a method that calculates vowels in the string s public int countvowels(string s) countvowel="0;" store total number of size="s.length();" for(int j="0;" < size; j++) char c="s.charAt(j);" if(isvowel(c)) vowel found! increase count by + 1; countvowel; main static void main(string argvs[]) creating an object class charatexample6 obj="new" charatexample6(); str="Javatpoint is a great site for learning Java." ; noofvowel="obj.countVowels(str);" system.out.println(\'string: \' str); system.out.println(\'total are: \'+ \' \'); noofvowel); pre> <p> <strong>Output:</strong> </p> <pre> String: Javatpoint is a great site for learning Java. Total number of vowels in the string are: 16 String: One apple in a day keeps doctor away. Total number of vowels in the string are: 13 </pre> <hr></al.size();>
=str.length()-1;>=str.length()-1;>