check string with delimiter expected - android

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?

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
}

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
}

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
}

Related

After split array gives only first character

I have a value in the database table that I would like to split by | the value is Company|company.pdf|images.pdf. When I run the following code, it only returns C in the Debug.
What am I doing wrong?
String cname = null;
String cpdf = null;
String cimages = null;
String catGetGeneralNameSQL = "SELECT * FROM categorymeta WHERE key = 'category_general' AND company = " + dashboard_company_id;
Cursor catGetGeneralNameQuery = myDB.rawQuery(catGetGeneralNameSQL, null);
while(catGetGeneralNameQuery.moveToNext()){
String name = catGetGeneralNameQuery.getString(catGetGeneralNameQuery.getColumnIndex("value"));
String[] separated = name.split("|");
Log.d("LOG", separated[1]);
}
It's because the split() method take a regular expression as parameter, and | is a reserved character in regexp.
Try with : \\| to escape it.
public static void main(String[] args) {
String test = "Company|company.pdf|images.pdf";
String[] result = test.split("\\|");
System.out.println(result[1]);
}
It outputs :
company.pdf
See the split() method documentation : https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
The pipe (without being escaped) is used in regular expressions to separate alternate matching patterns, eg: aaa|bbb will match "aaa" or "bbb", that's why it's matching every single character when not escaped.
Hope it helps.
You need to escape the original special character:
String[] separated = name.split("\\|");
use:
String[] b = a.split("\\|");
it will work fine with this

Android comparing strings with == to each objects

I'm coming from C#, so typically I try to relate everything that i'm doing.
I cannot figure out why the below statement doesn't work. Basically String val = "admin". Then an I have an if statement, however the if statement is always false. I'm sure it's something simple.
Thanks!
EditText edt = (EditText) findViewById(R.id.email);
//String val = edt.getText().toString();
String val = "admin";
EditText edt2 = (EditText) findViewById(R.id.password);
String val2 = edt2.getText().toString();
if(val.toString() == "admin") {
String hero = val;
}
You should use
if (val.equals("admin")) {
String hero = val;
}
instead of using an equal sign. Using an equal sign in java is asking if they're the same object, which will be false even if the strings are the same.
Also, be careful with what you're doing inside of the if statement, because the variable "hero" won't be accessible outside of that block.
In Java you can't compare strings using ==
You need to change your if statment like this
if(val.equals("admin")){}
First of all you have never changed the value of String val to anything so there is no need to try convert it to a string in your if statement.
String val = "admin";
if (val == "admin") {
//code here
}else{
//code here
}
Hope this helps
In java, == operator check the address of each value, and equals() method check the value.
So If you want to compare the value of each string, you should use the equals() method.
Please search for the concept of 'call by reference' and 'call by value'.
And you already declare val to String, so it didn't need toString().
if(val.equals("admin")) {
String hero = val;
}
I'm surprised no one mentioned the difference between .matches() and .equals() depending on your needs, what you could also be looking for is .matches()
if(val.toString().matches("admin")) {
String hero = val;
}
Matches checks the match of a String to a regular expression pattern, not the same string.
For example:
"hello".equals(".*e.*"); // false
"hello".matches(".*e.*"); // true
use .equals() instead of ==.
for example:
if (val.equals("admin")) ...

How can i get few characters from String?

I want to retrieve few characters from string i.e., String data on the basis of first colon (:) used in string . The String data possibilities are,
String data = "smsto:....."
String data = "MECARD:....."
String data = "geo:....."
String data = "tel:....."
String data = "MATMSG:....."
I want to make a generic String lets say,
String type = "characters up to first colon"
So i do not have to create String type for every possibility and i can call intents according to the type
It looks like you want the scheme of a uri. You can use Uri.parse(data).getScheme(). This will return smsto, MECARD, geo, tel etc...
Check out the Developers site: http://developer.android.com/reference/android/net/Uri.html#getScheme()
Note: #Alessandro's method is probably more efficient. I just got that one off the top of my head.
You can use this to get characters up to first ':':
String[] parts = data.split(":");
String beforeColon = parts[0];
// do whatever with beforeColon
But I don't see what your purpose is, which would help giving you a better solution.
You should use the method indexOf - with that you can get the index of a certain char. Then you retrieve the substring starting from that index. For example:
int index = string.indexOf(':');
String substring = string.substring(index + 1);

Subtracting string from a string [Android]

I have following two string:
String one:
"abcabc/xyzxyz/12345/random_num_09/somthing_random.txt"
String Two:
"abcabc/xyzxyz/12345/"
What i want to do is attach path "random_num_09/somthing_random.txt" from string one two string two. So how can i subtract string two from string one and then attach remaining part to string two.
I have tried to do it by searching for the second last "/" in the string one and then doing sub string and attaching it to string two.
But is there any better way of doing it.
Thanks.
I think the best way is to use substrings, as you said:
String string_one = "abcabc/xyzxyz/12345/random_num_09/somthing_random.txt";
String string_two = "abcabc/xyzxyz/12345/";
String result = string_two + string_one.substring(string_one.indexOf(string_two)+1));
The other possibility is to use regex, but you would still be doing concatenation to get the result.
Pattern p = Pattern.compile(string_two+"(.*)");
Matcher m = p.matcher(string_one);
if (m.matches()) {
String result = string_two+m.group(1);
}
rather that a substring, replace is simpler to use:
String string1 = "abcabc/xyzxyz/12345/random_num_09/somthing_random.txt";
String string2 = "abcabc/xyzxyz/12345/";
String res = string2 + string1.replace(string2, "");

Android String Array Manipulation

I have a lengthy string in my Android program.
What I need is, I need to split each word of that string and copy that each word to a new String Array.
For eg: If the string is "I did android program" and the string array is named my_array then each index should contain values like:
my_array[0] = I
my_array[1] = did
my_array[2] = Android
my_array[3] = Program
A part of program which I did looks like this:
StringTokenizer st = new StringTokenizer(result,"|");
Toast.makeText(appointment.this, st.nextToken(), Toast.LENGTH_SHORT).show();
while(st.hasMoreTokens())
{
String n = (String)st.nextToken();
services1[i] = n;
Toast.makeText(appointment.this, st.nextToken(), Toast.LENGTH_SHORT).show();
}
Can any one please suggest some ideas..
Why not use String.split() ?
You can simply do
String[] my_array = myStr.split("\\s+");
Since '|' is a special character in regular expression, we need to escape it.
for(String token : result.split("\\|"))
{
Toast.makeText(appointment.this, token, Toast.LENGTH_SHORT).show();
}
You can use String.split or Android's TextUtils.split if you need to return [] when the string to split is empty.
From the StringTokenizer API docs:
StringTokenizer is a legacy class that
is retained for compatibility reasons
although its use is discouraged in new
code. It is recommended that anyone
seeking this functionality use the
split method of String or the
java.util.regex package instead.
Since String is a final class, it is by default immutable, which means you cannot make changes to your strings. If you try, a new object will be created, not the same object modified. Therefore if you know in advance that you are going to need to manipulate a String, it is wise to start with a StringBuilder class. There is also StringBuffer for handling threads. Within StringBuilder there are methods like substring():
substring(int start)
Returns a new String that contains a subsequence of characters currently contained in this character sequence.
or getChars():
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Characters are copied from this sequence into the destination character array dst.
or delete():
delete(int start, int end)
Removes the characters in a substring of this sequence.
Then if you really need it to be a String in the end, use the String constructor(s)
String(StringBuilder builder)
Allocates a new string that contains the sequence of characters currently contained in the string builder argument.
or
String(StringBuffer buffer)
Allocates a new string that contains the sequence of characters currently contained in the string buffer argument.
Although to understand when to use String methods and when to use StringBuilder, this link or this might help. (StringBuilder comes in handy with saving on memory).

Categories

Resources