Huawei Online Programming Questions Series-4-String Separation


Problem Description:

Problem Description

1. The question involves knowledge points.

  • Make an infinite input scanner.hasNext().
  • String handling.

2. Solve it yourself.

  • Two inputs, one at a time.
  • Judging the character length, if it is a multiple of 8, it is divided directly according to 8 bits. If it is not a multiple of 8, add 0 to a multiple of 8, and then divide it.
package com.chaoxiong.niuke.huawei;
import java.util.Objects;
import java.util.Scanner;
public class HuaWei_4 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String string1 = in.nextLine();
            String string2 = in.nextLine();
            String []strArr = new String[13];//字符串最长为100 100/8=13
            // 每次处理一个字符串
            int strArrIndex = SegmentStr(string1.trim(),strArr);
            if(strArrIndex!=0){
                for(int i=0;i<strArrIndex;i++){
                    System.out.println(strArr[i]);
                }
            }
            strArrIndex = SegmentStr(string2, strArr);
            if (strArrIndex != 0) {
                for(int i=0;i<strArrIndex;i++){
                    System.out.println(strArr[i]);
                }
            }
        }
    }
    private static int SegmentStr(String str, String[] strArr) {
    // 字符串为空,不做处理.
        if(Objects.equals(str, "") ||str==null){return 0;}
        char [] charArr = str.toCharArray();
        char[] tmpCharArr;
        if(charArr.length%8==0){//可以整除8直接切分.
            tmpCharArr = new char[charArr.length];
        }else {
        // 不能整除8,则取整除之后加上1.
            tmpCharArr = new char[(charArr.length/8+1)*8];
        }
        // 切分操作.
        for(int i=0;i<tmpCharArr.length;i++){
            if(i<charArr.length){
                tmpCharArr[i] = charArr[i];
            }else {
                tmpCharArr[i] = '0';
            }
        }
        // 打印.
        int strArrIndex  = 0;
        for(int i=0;i<(tmpCharArr.length/8);i++){
            String tmp =  new String(tmpCharArr, i*8, 8);
            strArr[strArrIndex] =tmp;
            strArrIndex++;
        }
        return strArrIndex;
    }
}

3. Quality answers.

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){        
            String s = new String(sc.nextLine());
            if(s.length()%8 !=0 )
                s = s + "00000000";
            while(s.length()>=8){
                System.out.println(s.substring(0, 8));
                s = s.substring(8);
            }
        }
    }
}

4. Summary of this question.

String.substring(index)Refers to the character after index in the string. 123.substring(2) out:3.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325865897&siteId=291194637