Martynas
Martynas

Reputation: 627

check string with delimiter expected

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.

Upvotes: 3

Views: 607

Answers (3)

RMachnik
RMachnik

Reputation: 3684

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

}

Upvotes: 1

Waqar Ahmed
Waqar Ahmed

Reputation: 5068

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
}

Upvotes: 1

Ahmed Ekri
Ahmed Ekri

Reputation: 4651

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
}

Upvotes: 1

Related Questions