简体   繁体   中英

Extracting only number in a string from a starting point

Suppose I'm taking a string from a file that has decoded huffman text and the frequency of the characters inside it.Example the taken string is:"000111010 h:2#c:1" I want to take only 2 and 1 and put them into an arrayList of integers called frequencies. This is the method I have written for it but it doesn't seem to work:

public void extractFrequency() {
     char[] stringArray= new char[finalText.length()];
     stringArray=finalText.toCharArray();
     boolean startingNow=false;
     
     for (int i = 0; i < stringArray.length; i=+3) {
        
        if(stringArray[i]==' ')
            startingNow=true;
        
        if(startingNow=true) {
            frequencies.add((int)stringArray[i]);
            i++;
        }
        }
    System.out.println(frequencies);
}


Could you please help me?

Along with checking startingNow is true, check whether the current character is a digit or not. If it is a digit, then add it to the list. But I don't understand why you are doing i+=3 in loop. This might work for you. I am subtracting 48 while adding it to the list, to obtain the original digit, as in Character systems '0' starts from 48.

public void extractFrequency() {
     char[] stringArray= new char[finalText.length()];
     stringArray=finalText.toCharArray();
     boolean startingNow=false;
     
     for (int i = 0; i < stringArray.length; i++) {
        
        if(stringArray[i]==' ')
            startingNow=true;
        
        if(startingNow==true && Character.isDigit(stringArray[i])) {//should be startingNow==true not startingNow=true
            frequencies.add(stringArray[i] - 48);
        }
        }
    System.out.println(frequencies);
}

It doesn't work because you have an error in your code if(startingNow=true) should be if(startingNow==true)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM