3

I want to split string got from bluetooth. i'm using

StringTokenizer  splitStr = new StringTokenizer(readMessage, "\\|");
String numberSpeed = splitStr.nextToken();  //splitStr[0].replaceAll("\\D+","");
String numberTorque = splitStr.nextToken();  //splitStr[1].replaceAll("\\D+","");
numberSpeed = numberSpeed.replaceAll("\\D+","");
numberTorque = numberTorque.replaceAll("\\D+","");

Did it with split string before. If i get corupted data without delimiter the app crashes while trying to do impossible.

  • How to check if there is delimiter or not and then proceed split or skip it?
Martynas
  • 627
  • 2
  • 8
  • 28

3 Answers3

1

you can check for delimeter in string by contains() method

if(str.contains("_your_delimiter")) {   //for safe side convert your delimeter and search string to lower case using method toLowerCase()
     //do your work here
}
Waqar Ahmed
  • 5,005
  • 2
  • 23
  • 45
  • `if(readMessage.contains("|")){ StringTokenizer splitStr = new StringTokenizer(readMessage, "\\|"); numberSpeed = splitStr.nextToken().replaceAll("\\D+",""); numberTorque = splitStr.nextToken().replaceAll("\\D+",""); }` still it tries to split it and crashes – Martynas May 20 '14 at 12:23
  • can you post the logcat. i mean to say which exception it throws. – Waqar Ahmed May 20 '14 at 12:24
  • It worked actually... Do not know what i changed, but it worked :D – Martynas May 20 '14 at 12:30
  • And how to check if string contains number? `if(str.contains("_your_delimiter && D+")) {`??? Sorry i dont know all these \\DD and so on commands... – Martynas May 20 '14 at 13:15
  • see here..this might help you what you want to do. see the accepted answer...http://stackoverflow.com/questions/18590901/check-if-a-string-contains-numbers-java – Waqar Ahmed May 20 '14 at 16:44
1

Try this, I use it in my app.

String container = numberSpeed ;
String content = "\\D+";
boolean containerContainsContent = StringUtils.containsIgnoreCase(container, content);

It will return true if it has delimiter, and false it not.

Use that with an if statement. ex.

if(containerContainsContent){
//split it 
} else {
//skip it
}
Ahmed Ekri
  • 4,601
  • 3
  • 23
  • 42
1

This is quote from tokenizer docs: StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code.

Try to user String.split() instead.

if(str.contains(DEILIMITER)) {
     String tab[] = str.split(DEILIMITER);
    //enter code here

}
RMachnik
  • 3,598
  • 1
  • 34
  • 51