toCharArray()的用途
将字符串对象中的字符串转换为一个字符数组
simple example
|
|
输出结果:
myChar[1]=b
Attention
让我们简单地看一下这个例子1234567String str="hello";char c[]={'h','e','l','l','o'};char ch[]=str.toCharArray();if(ch.equals(c))System.out.println("true");elseSystem.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: 1020>
- Each sub-string containing k same characters should be encoded to “kX” where “X” is the only character in this sub-string.
- 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
ABBCCCSample Output
ABC
A2B3Canswer
12345678910111213141516171819202122232425262728293031323334353637import 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);}}}