Pick a specific part of a string using ANDROID split method

Asked

Viewed 1,009 times

0

I made a code to display processes on android but when printing in a text view, it prints the PID, process name, memory cpu usage etc. The display is this way

958  2   0% S    22 577164K  42624K  bg u0_a63   com.snaptube.premium

i would like to print only "with.snaptube.premium"

I tried to use the split method but did not succeed

my code for displaying the processes is so

  p = Runtime.getRuntime().exec(command); // uso para utilizar comandos do linux
  p.waitFor();
  String line = ""; // string que contem a linha com as informações do processo
  BufferedReader reader = new BufferedReader(new  InputStreamReader(p.getInputStream()));                      
  BufferedReader bufferedReader = new BufferedReader(inputStreamReader);            

                while ((line = reader.readLine()) != null) {
                System.out.println(line);
                output.append(line + "\n"); // impressao dos processos no textview

created a String variable [] helper and assigned it the line.lengh() - 1 and used line.split("") to separate the string by whitespace

1 answer

1


The function is not required split.
If it is the last part of the text it is simpler to use the methods substring and lastIndexOf class String

String parteFinal = texto.substring(texto.lastIndexOf(" ") + 1)

The method substring(int start) returns the part of the string starting at the index passed to the parameter until the end of the string.

To find out which index to go to substring() we use the method lastIndexOf(String string) which returns the index of the last occurrence of the string passed as parameter.

                                                 _substring(start+1)_
                                                 |                  |
958  2   0% S    22 577164K  42624K  bg u0_a63   com.snaptube.premium
                                                ^
                                                |
                                              start = texto.lastIndexOf(" ")
  • It went well Thank you very much Could you explain to me how to understand°? Knew the substring but not the lastofIndex ?

  • I edited the answer with a short explanation.

  • got it now , in the output of the text, are leaving 3 strings that I would not like to leave, one of them is the use of cpu and a PID, (only comes out once) but are varying 10-16 17:12:06.460 3092-3092/? I/System.out: 0% 10-16 17:12:06.460 3092-3092/? I/System.out: 1170 10-16 17:12:06.460 3092-3092/? I/System.out: Name else is working. do you know how I could ignore these 3 strings that come out? and start printing from the 4th string that is where the processes begin?

  • You are correct to create a new question. I invite you to see how the website works on tour and here how to proceed when a reply has been useful to you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.