Java String转char
1 Java String转char的介绍
我们可以使用String类的charAt() 方法在Java中将String转换为char。
2 Java String转char的声明
charAt() 方法返回指定索引的单个字符。charAt() 方法的签名如下:
public char charAt(int index)
3 Java String转char的案例1
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
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);
}}
输出结果为:
1st character is: h
4 Java String转char的案例2
public class StringToCharExample2{
public static void main(String args[]){
String s="hello";
for(int i=0; i<s.length();i++){
char c = s.charAt(i);
System.out.println("char at "+i+" index is: "+c);
}
}}
输出结果为:
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
5 Java String转char的案例3
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
public class StringToCharExample3{
public static void main(String args[]){
String s1="hello";
char[] ch=s1.toCharArray();
for(int i=0;i<ch.length;i++){
System.out.println("char at "+i+" index is: "+ch[i]);
}
}}
输出结果为:
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
热门文章
优秀文章