logo

Java Pretvori niz v char

Lahko se pretvarjamo Niz za char v Javi uporabo charAt() metoda razreda String.

Java Pretvori niz v char

Metoda charAt() vrne samo en znak. Če želite dobiti vse znake, lahko uporabite zanko.

java pozdravljen svet

Podpis

Metoda charAt() vrne en znak določenega indeksa. The podpis metode charAt() je podan spodaj:

 public char charAt(int index) 

Java String to char Primer: metoda charAt().

Oglejmo si preprosto kodo za pretvorbo niza v char v javi z uporabo metode charAt().

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

Oglejmo si preprost primer pretvorbe niza v char v Javi.

 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); }} 
Preizkusite zdaj

Izhod:

 1st character is: h 

Oglejmo si še en primer pretvorbe vseh znakov niza v 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++){>

Java String to char Primer: metoda toCharArray().

Oglejmo si preprosto kodo za pretvorbo niza v char v javi z uporabo metode toCharArray(). Metoda toCharArray() razreda String pretvori ta niz v niz znakov.

 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++){>