JAVA中toCharArray()的用法

toCharArray()的用途

将字符串对象中的字符串转换为一个字符数组

simple example

1
2
3
String myString="abcd";
char myChar[]=myString.toCharArray();
System.out.println("myChar[1]="+myChar[1]);

输出结果:
myChar[1]=b

Attention

让我们简单地看一下这个例子

1
2
3
4
5
6
7
String str="hello";
char c[]={'h','e','l','l','o'};
char ch[]=str.toCharArray();
if(ch.equals(c))
System.out.println("true");
else
System.out.println("false");

这个例子的输出结果是false:因为数组是对象,数组没有重写equals方法,默认还是比较的内存地址,你是两个不同的数组,地址当然不一样了!
你可以用Java.util.Arrays.equals(ch,c);进行比较
c和ch是不同的对象数组,虽然数组里面的值是一样的,但是他们的存储地址并不一样。按你的程序来,运行结果是false是正确的。
数组是对象不是基本变量,不可以这样比较的。因为存储地址不一样。字符数组以/0结尾

exercise

HDOJ<1020>-Encoding Problem
request
Given a string containing only ‘A’ - ‘Z’, we could encode it using the following method:

  1. Each sub-string containing k same characters should be encoded to “kX” where “X” is the only character in this sub-string.
  2. If the length of the sub-string is 1, ‘1’ should be ignored.

    Input

    The first line contains an integer N (1 <= N <= 100) which indicates the number of test cases.
    The next N lines contain N strings. Each string consists of only ‘A’ - ‘Z’ and the length is less than 10000.

    Output

    For each test case, output the encoded string in a line.

    Sample Input

    2
    ABC
    ABBCCC

    Sample Output

    ABC
    A2B3C

    answer

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    import java.util.Scanner;
    public class Main
    {
    public static void main(String agrs[])
    {
    Scanner read = new Scanner (System.in);
    int n = read.nextInt();
    read.nextLine();
    while(n--!=0)//跳出循环条件
    {
    String str = read.nextLine();
    char get[]= str.toCharArray();//转换成字符数组
    String put="";
    for(int i=1,count=1;i<=str.length();i++)
    {
    if(i==str.length())
    {
    if(count!=1)
    put+=count;
    put+=get[i-1];
    break;//跳出循环条件
    }
    if(get[i]==get[i-1])
    count++;
    else
    {
    if(count!=1)
    put+=count;
    put+=get[i-1];
    count=1;
    }
    }
    System.out.println(put);
    }
    }
    }