I have a string containing messages. The string looks like this:
bill:hello;tom:hi;bill:how are you?;tommy:hello!; ...
I need to split the string into several srings, on the characters : and ;.
For now, I have split the string on ; and i could add the results in list elements.
List<Message> listMessages = new ArrayList<Message>();
StringTokenizer tokenizer = new StringTokenizer(messages, ";");
String result = null;
String uname = "";
String umess = "";
while (tokenizer.hasMoreTokens()) {
result = tokenizer.nextToken();
listMessages.add(new Message(result, ""));
}
I still have to do this on the : to have the two resulting strings in my list element, and I tried something like that:
List<Message> listMessages = new ArrayList<Message>();
StringTokenizer tokenizer = new StringTokenizer(messages, ";");
String result = null;
String uname = "";
String umess = "";
while (tokenizer.hasMoreTokens()) {
result = tokenizer.nextToken().split(":");
uname = result[0];
umess = result[1];
listMessages.add(new Message(result[0], result[1]));
}
But I got this error, that I don't understand?
01-23 17:12:19.168: E/AndroidRuntime(711): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.appandroid/com.example.appandroid.ListActivity}: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
Thanks in advance to look at my problem.
Instead of using StringTokenizer, you can use String.split(regex) to split based on two delimiters like below:
String test="this: bill:hello;tom:hi;bill:how are you?;tommy:hello!;";
String[] arr = test.split("[:;]");
for(String s: arr){
System.out.println(s);
}
Output:
this
bill
hello
tom
hi
bill
how are you?
tommy
hello!
EDIT:
from #njzk2 comments if you just wanna use StringTokenizer you can use one of its overloaded constructor which takes 2 args .
StringTokenizer str = new StringTokenizer(test, ":;");
Related
In java i have to cut word "getenforce" from string.
problem is the word I receive is sometimes cut off. For example i receive "etenforce", or "tenforc".
I could assume at least 4 letters will come in and filter it like that:
//st ---> this is string
st = st.replace("getenforce", "");
st = st.replace("gete", "");
st = st.replace("eten", "");
st = st.replace("tenf", "");
...
st = st.replace("orce", "");
is there some better, more elegant way?
You can use a for loop instead of doing this line by line.
String theWord = "getenforce";
st = st.replace(theWord, "");
//check all the sequences in loop
for(int i=0; i<theWord.length()-3;i++){
st=st.replace(theWord.subSequence(i, i+4), "");
}
I believe this will resolve your query
List<String> strings = Arrays.asList("your sentence with word gete".split(" "));
List<String> filtered = strings.stream().filter(s1 -> !s1.contains("gete")).collect(Collectors.toList());
I have the following string in Java. For Example:
String abc = "nama=john; class=6; height=170; weight=70";
How can I extract the value of height from the String?
Outputs: height=170
This is the code I have written so far:
String abc = "nama=john; class=6; height=170; weight=70";
String[] tokens = abc.split("; ");
List<String> listString = new ArrayList<String>();
String mod = new String();
for (String s : tokens) {
mod = s;
System.out.println(s);
listString.add(mod);
}
System.out.println(listString.size());
But I do not get the value height. Instead, I get value of height as a String.
Thanks.
With this Code-Snippet:
String abc = "nama=john; class=6; height=170; weight=70";
for(String sa : abc.split(";")){
System.out.println(sa.trim());
}
you generate this output:
nama=john
class=6
height=170
weight=70
if you want to add a specific String into a list you put the sa.trim() at the List.add parameter. To find the height-String you can use:
if(sa.trim().startsWith("height")) and you have the needed String.
you can use this regex:
(?<=height=)(\d+)(?=;|\Z)
if you want to implement this, you can do it like this:
Pattern pattern = Pattern.compile("(?<=height=)(\\d+)(?=;|\\Z)");
// create matcher object.
Matcher m = pattern.matcher(abc);
if (m.find())
{
String height = m.group(0);
}
else
{
System.out.println("not found");
}
here, you have an example: https://regex101.com/r/iM3gY0/2
and here you have an executable snipped: https://ideone.com/azngNt
If you want all parameter, you can use this regex:
(\w+)=([\d|\w]+)(?=;|\"|\Z)
so you get as Pattern:
Pattern pattern = Pattern.compile("(\\w+)=([\d|\\w]+)(?=;|\\"|\\Z)");
and the Regex101 again: https://regex101.com/r/uT6uK1/3
#Fast Snail you are correct, but I think they wanted an integer value of it:
final String string = "nama=john; class=6; height=170; weight=70";
final String[] tokens = string.split("; ");
for (String token : tokens) {
if (token.contains("height")) {
System.out.println(token);
final String[] heightSplit = token.split("=");
Integer heightValue = new Integer(heightSplit[1]);
System.out.println("height=" + heightValue);
}
}
System.out.println(tokens.length);
This should do what you need.
Use String tokenizer
import java.util.StringTokenizer;
public class stringval {
StringTokenizer st = new StringTokenizer(" nama=john, class=6, height=170, weight=70;",",");{
while(st.hasMoreTokens()){
String abc=st.nextToken();
if(abc.equals("height=170")){
StringTokenizer s=new StringTokenizer(abc,"=");
while(s.hasMoreTokens()){
String str=s.nextToken();
if (s.equals("170")){
System.out.print(s);
break;
}
}
}
}
}
}
With Java 8 you can do the following:
Map<String, String> map = Arrays.stream("nama=john; class=6; height=170; weight=70".split(";"))
.map(s -> s.trim().split("="))
.collect(Collectors.toMap(s -> s[0], s -> s[1]));
System.out.println(map.get("height")); //170
Thanks Mr. MrT.
Code answer: Resolved.
String abc = "nama=john; class=6; height=170; weight=70";
String[] tokens = abc.split("; ");
List<String> listString = new ArrayList<String>();
String mod = new String();
for(String s:tokens){
mod =s;
System.out.println(s);
listString.add(mod);
}
System.out.println(listString.size());
for(String abcd :listString){
if(abcd.trim().startsWith("height")){
System.out.println(abcd);
}
}
I am taking creating a StringTokenizer like so and populating an ArrayList using the tokens:
LogUtils.log("saved emails: " + savedString);
StringTokenizer st = new StringTokenizer(savedString, ",");
mListEmailAddresses = new ArrayList<String>();
for (int i = 0; i < st.countTokens(); i++) {
String strEmail = st.nextToken().toString();
mListEmailAddresses.add(strEmail);
}
LogUtils.log("mListEmailAddresses: emails: " + mListEmailAddresses.toString());
11-20 09:56:59.518: I/test(6794): saved emails: hdhdjdjdjd,rrfed,ggggt,tfcg,
11-20 09:56:59.518: I/test(6794): mListEmailAddresses: emails: [hdhdjdjdjd, rrfed]
As you can see mListEmailAddresses is missing 2 values off the end of the array. What should I do to fix this. From my eyes the code looks correct but maybe I am misunderstanding something.
Thanks.
using hasMoreTokens is the solution
while(st.hasMoreTokens()){
String strEmail = st.nextToken().toString();
mListEmailAddresses.add(strEmail);
}
Use the following while loop
StringTokenizer st = new StringTokenizer(savedString, ",");
mListEmailAddresses = new ArrayList<String>();
while (st.hasMoreTokens()) {
String strEmail = st.nextToken();
mListEmailAddresses.add(strEmail);
}
Note, you don't need to call toString, nextToken will return the string.
Alternatively, you could use the split method
String[] tokens = savedString.split(",");
mListEmailAddresses = new ArrayList<String>();
mListEmailAddresses.addAll(Arrays.asList(tokens));
Note, the API docs for StringTokenizer state:
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.
st.countTokens() method calculates the number of times that this tokenizer's nextToken() method can be called before it generates an exception. The current position is not advanced.
To get all elements in ArrayList you should use following code
while(st.hasMoreTokens()) {
String strEmail = st.nextToken().toString();
mListEmailAddresses.add(strEmail);
}
right now I am a little bit confused. I want to manipulate this string with a tokenizer:
Bob:23456:12345 Carl:09876:54321
However, I use a Tokenizer, but when I try:
String signature1 = tok.nextToken(":");
tok.nextToken(" ")
I get:
12345 Carl
However I want to have the first int and the second int into a var.
Any ideas?
You have two different patterns, maybe you should handle both separated.
Fist you should split the space separated values. Only use the string split(" "). That will return a String[].
Then for each String use tokenizer.
I believe will works.
Code:
String input = "Bob:23456:12345 Carl:09876:54321";
String[] words = input.split(" ")
for (String word : words) {
String[] token = each.split(":");
String name = token[0];
int value0 = Integer.parseInt(token[1]);
int value1 = Integer.parseInt(token[2]);
}
Following code should do:
String input = "Bob:23456:12345 Carl:09876:54321";
StringTokenizer st = new StringTokenizer(input, ": ");
while(st.hasMoreTokens())
{
String name = st.nextToken();
String val1 = st.nextToken();
String val2 = st.nextToken();
}
Seeing as you have multiple patterns, you cannot handle them with only one tokenizer.
You need to first split it based on whitespace, then split based on the colon.
Something like this should help:
String[] s = "Bob:23456:12345 Carl:09876:54321".split(" ");
System.out.println(Arrays.toString(s ));
String[] so = s[0].split(":", 2);
System.out.println(Arrays.toString(so));
And you'd get this:
[Bob:23456:12345, Carl:09876:54321]
[Bob, 23456:12345]
If you must use tokeniser then I tink you need to use it twice
String str = "Bob:23456:12345 Carl:09876:54321";
StringTokenizer spaceTokenizer = new StringTokenizer(str, " ");
while (spaceTokenizer.hasMoreTokens()) {
StringTokenizer colonTokenizer = new StringTokenizer(spaceTokenizer.nextToken(), ":");
colonTokenizer.nextToken();//to igore Bob and Carl
while (colonTokenizer.hasMoreTokens()) {
System.out.println(colonTokenizer.nextToken());
}
}
outputs
23456
12345
09876
54321
Personally though I would not use tokenizer here and use Claudio's answer which splits the strings.
How can i isolate a String existed between two commas?
i.e. Angelo,Marco,Nick,Brandon,Paul
I want to retrieve the name Marco. Which is the most appropriate way? Should i use regex?If yes,can anyone explain me how?
The simplest solution is to use String.split(",")
like so:
String str = "Angelo,Marco,Nick,Brandon,Paul";
String[] myStrings = str.split(",");
String marco = myStrings[1];
Try this
String s = "Angelo,Marco,Nick,Brandon,Paul";
String array[] = s.split(",");
for (int i = 0; i < array.length; i++) {
System.out.println("element "+i+" "+array[i]);
}
You can use split e.g.
String[] names = "Angelo,Marco,Nick,Brandon,Paul".split(",");
// or
List<String> names = Arrays.asList("Angelo,Marco,Nick,Brandon,Paul".split(","));
// or
for(String name: "Angelo,Marco,Nick,Brandon,Paul".split(","))
System.out.println(name);
Well lets not make it complicated and use split() and Arrays.asList() method....
String str = "Angelo,Marco,Nick,Brandon,Paul";
String[] arr = str.split(",");
List<String> alist = new ArrayList<String>(Arrays.asList(arr);
String marco = alist.get(alist.indexOf("Marco"));
Voila..... its done... !!! Marco is with u now....
split string using comma separator.
**try it**
String str = "Angelo,Marco,Nick,Brandon,Paul";
String lines[]= str.split(",");
String name = lines[1];