One small practice daily (string compression)

Title description: String compression:

  • Compress the consecutive characters in the original string according to the number of occurrences.
  • Input: AACBBBDDDDFFX
  • Output: A2C1B3D5F2X1

Ideas:

1. Get input:
Use the Scanner class to create an input object (pay attention to the package, that is, the first line of the program below), get the string to be compressed, and define a number counter and initialize it to 1, which is used to record the current number of characters , Because the current character appears at least once.
2. Compression
Use the for loop to first obtain the current character and the next character ( charAt() ), and then judge whether the two are the same. If they are the same, the counter will accumulate. If they are not the same, the current character and the number of occurrences will be output (Note: Output in string form, and use ( System.out.print() ). At this time, the number is reset to 1.
But at this time, there is a problem. When the loop reaches the last character, the next character cannot be obtained and appears Subscript out-of-bounds ( ArrayIndexOutOfBoundsException ) exception, so before we get the next character, we should first determine whether the character is the last character, if it is the last character, output the character and the counter value.

import java.util.Scanner;
public class Test0 {
    
    

		public static void main(String[] args) {
    
    
		Scanner input=new Scanner(System.in);	
		String arr=input.next();
		int number=1;
		
		//遍历每个字符
		for(int i=0;i<arr.length();i++){
    
    
			//获取当前字符
			char c=arr.charAt(i);
			
			//判断是否为最后一个字符
			if(i==arr.length()-1){
    
    
				System.out.println(c + "" + number);
				break;
			}
			
			//获取下一个字符
			char next=arr.charAt(i+1);
			
			if(c==next){
    
    
				number++;//次数累加
			}else{
    
    
				//输出
				System.out.print(c+"" + number);
				//出现次数重置为1
				number=1;
			}
		}
	}

}

Guess you like

Origin blog.csdn.net/weixin_51529267/article/details/112732266