JAVA中的charAt()和toCharArray()

来源:互联网 发布:soap协议java 编辑:程序博客网 时间:2024/05/06 00:05

1、charAt()功能类似于数组,可以把字符串看作是char类型的数组,它是把字符串拆分获取其中的某个字符;返回指定位置的字符。

charAt(i),i为int类型,i从0开始。

例如:

String str01 = "hello123";

char c = str01.charAt(1);  //返回位置为1的字符

output:c=e

解析:类似于String [] str01 = {'h','e','l','l','o','1','2','3'};

 

 

2、toCharArray()的用法:将字符串对象中的字符转换为一个字符数组

例如:

public class Program
{
    public static void main(String[] args)
    {
        String str = "This is a String.";
        // Convert the above string to a char array.
        char[] arr = str.toCharArray();

        // Display the contents of the char array.
        System.out.println(arr);
    }
}

/*
Output:
This is a String.
*/

0 0