-1

I have tried to replace a string in an array then conver it to string but it was not like I want. Here is my example:

    String data = "ABC   00 0 03 54            BTT";
    String[] tokens = data.split("\\s+");
    for(int i=0; i<tokens.length; i++){
        if(tokens[i] == "BTT"){
           tokens[i] = tokens[i].replace("BTT"," ");
        }
    }
    data = Arrays.toString(tokens);
    Log.log(Log.VRB, "DEBUG: field =" + data);

OUTPUT: DEBUG: field =[ABC, 00, 0, 03, 54, BTT]

But I had tried to get this output: DEBUG: field = ABC 00 0 03 54

Can anyone give me the idea how can I fix it?

Thanks.

  • 3
    Loop on the array and print the values yourself... – brso05 Sep 30 '16 at 12:54
  • 2
    Use tokens[i].equals("BTT"), '==' in Java does not work a you'd think for string comparison. – Jacob H Sep 30 '16 at 12:55
  • Ok Jacob, I will change the comparing like tokens[i].equals("BTT") but the issue is my code doesnt replace BTT with space or delete it. also the output is not like input as ABC 00 0 03 54. it is like [ABC, 00, 0, 03, 54, BTT] – Oscar Sayin Sep 30 '16 at 13:01
  • check my answer below that solves your issue – Wael Sep 30 '16 at 13:03

5 Answers5

1
String data = "ABC   00 0 03 54            BTT";
String[] tokens = data.split("\\s+");
data = Arrays.stream(data.split("\\s+"))
            .filter(s -> !"BTT".equals(s))
            .collect(Collectors.joining(" "));
Log.log(Log.VRB, "DEBUG: field = " + data);

Output => DEBUG: field = ABC 00 0 03 54
Vivek G
  • 186
  • 3
0

Dont use == if you want to compare value of 2 strings, because it is used for working with their address in heap.

Please replace tokens[i] == "BTT" into tokens[i].equals("BTT") .It will be compare their value.

Sorry for not-good English :)

Tinh Huynh
  • 76
  • 2
  • 6
-1

Use .equals() method then iterate over the array to print it as string as follows:

    String data = "ABC   00 0 03 54            BTT";
    String[] tokens = data.split("\\s+");
    for(int i=0; i<tokens.length; i++){
        if(tokens[i].equals("BTT")){
           tokens[i] = tokens[i].replace("BTT"," ");
        }
    }
    data = Arrays.toString(tokens);
    Log.log(Log.VRB, "DEBUG: field =" + data);       

  StringBuffer b =new StringBuffer();
  for(int i = 0; i< tokens.length; i++)
  {
      b.append(tokens[i]);

      if(i< tokens.length -1)
      {
          b.append(" ");
      }
  }

  Log.log(Log.VRB, "DEBUG: field =" + b.toString());
Wael
  • 1,533
  • 4
  • 20
  • 35
-1

There is this method for Strings: .substring(int beginning, int end);

 Log.log(Log.VRB, "DEBUG: field =" + data.substring(1, data.length()-1));  

It removes the first and last char in the string (the [ and ]).

-1

Use String Class replace and replaceAll utility methods.

String data = "ABC 00 0 03 54 BTT";

Log.log(Log.VRB, "DEBUG: field =" + data.trim().replaceAll(" +", " ").replace("BTT", ""));