Reputation: 53
My app reads a value of a NFC tag which contains plain text, to then cut the read String up. The string should be as follow: "r=v;b=v;g=v;n=v;p=v;m=v;s=v" I want to read the "v" characters, since they are divided by the ; character, and i remember there being a function that let me divide strings like this, how do i do it? The v value isn't constant, it could span 1 position like it could span 3 or 4. The app is for Android phones, written in Java on Android Studio.
Upvotes: 1
Views: 162
Reputation: 6237
You are asking about String method .split()
it's splits string into array and so for you question, since split can work with regex you can split exactly for needed patterns like this:
String givenString="r=v;b=v;g=v;n=v;p=v;m=v;s=v";
String[]vs=givenString.split("([;]?[a-z]{1}[=])");
for(String v: vs){System.out.println(v);}//prints all v
Regex explanation:
Edit: if you use split by only semicolon (as @cvester suggested), you get the whole entry string, such as: "r=v","b=v", etc.. in this case you can iterate over all entries and then make one more split by equals "=" like this:
String []entries=givenString.split(";");
for (String entry:entries){
String []vs=entry.split("=");
System.out.println(vs[1]);//prints all v
}
Upvotes: 2
Reputation: 2943
You could use regex to avoid looping
String input = "r=v;b=v;g=v;n=v;p=v;m=v;s=v";
input.trim().replaceAll("([a-zA-Z]=)+","").replaceAll(";",""));
Upvotes: 0
Reputation: 5629
Use String#split()
or you could create your own logic.
String string = "r=v;b=asfasv;g=v;n=asf;p=v;m=v;s=vassaf";
String word = "";
int i = 0;
ArrayList<String> list = new ArrayList();
while(i < string.length())
{
if(string.charAt(i) == '=')
{
i++;
while( i < string.length() && string.charAt(i) != ';' )
{
word += string.charAt(i);
i++;
}
list.add(word);
System.out.println(word);
word = "";
}
i ++;
}
if(!word.equals(""))
list.add(word);
System.out.println(list);
Upvotes: 0
Reputation: 696
Java has a split function on a String. http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
So you can just use split(";");
Upvotes: 2