logo

Java Konwertuj ciąg na znak

Możemy dokonać konwersji Ciąg do znaku w Javie za pomocą charAt() metoda klasy String.

Java Konwertuj ciąg na znak

Metoda charAt() zwraca tylko pojedynczy znak. Aby uzyskać wszystkie znaki, możesz użyć pętli.

co to jest zestaw skrótów w Javie

Podpis

Metoda charAt() zwraca pojedynczy znak o określonym indeksie. The podpis metody charAt() podano poniżej:

 public char charAt(int index) 

Java String na char Przykład: metoda charAt().

Zobaczmy prosty kod konwertujący String na znak w Javie przy użyciu metody charAt().

 String s='hello'; char c=s.charAt(0);//returns h 

Zobaczmy prosty przykład konwersji String na char w Javie.

 public class StringToCharExample1{ public static void main(String args[]){ String s='hello'; char c=s.charAt(0);//returns h System.out.println('1st character is: '+c); }} 
Przetestuj teraz

Wyjście:

 1st character is: h 

Zobaczmy inny przykład konwersji wszystkich znaków ciągu na znak.

 public class StringToCharExample2{ public static void main(String args[]){ String s=&apos;hello&apos;; for(int i=0; i<s.length();i++){ char c="s.charAt(i);" system.out.println('char at '+i+' index is: '+c); } }} < pre> <span> Test it Now </span> <p>Output:</p> <pre> char at 0 index is: h char at 1 index is: e char at 2 index is: l char at 3 index is: l char at 4 index is: o </pre> <h2>Java String to char Example: toCharArray() method</h2> <p>Let&apos;s see the simple code to convert String to char in java using toCharArray() method. The toCharArray() method of String class converts this string into character array.</p> <pre> public class StringToCharExample3{ public static void main(String args[]){ String s1=&apos;hello&apos;; char[] ch=s1.toCharArray(); for(int i=0;i<ch.length;i++){ system.out.println('char at '+i+' index is: '+ch[i]); } }} < pre> <span> Test it Now </span> <p>Output:</p> <pre> char at 0 index is: h char at 1 index is: e char at 2 index is: l char at 3 index is: l char at 4 index is: o </pre></ch.length;i++){></pre></s.length();i++){>

Ciąg Java na znak Przykład: metoda toCharArray().

Zobaczmy prosty kod konwertujący ciąg znaków na znak w Javie przy użyciu metody toCharArray(). Metoda toCharArray() klasy String konwertuje ten ciąg znaków na tablicę znaków.

 public class StringToCharExample3{ public static void main(String args[]){ String s1=&apos;hello&apos;; char[] ch=s1.toCharArray(); for(int i=0;i<ch.length;i++){ system.out.println(\'char at \'+i+\' index is: \'+ch[i]); } }} < pre> <span> Test it Now </span> <p>Output:</p> <pre> char at 0 index is: h char at 1 index is: e char at 2 index is: l char at 3 index is: l char at 4 index is: o </pre></ch.length;i++){>