String between two commas Java - java

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];

Related

Extract Substring from String java

I want to extract specific substrings from a string:
String source = "info1 info1ContentA info1ContentB info3 info3ContentA info3ContentB"+
"info2 info2ContentA";
The result should be:
String info1 ="info1ContentA info1ContentB";
String info2 ="info2ContentA";
String info3 ="info3ContentA info3ContentB";
For me it's very difficult to extract the informations, because sometimes after "info" their are one, two or more content informations. Another problem that occurs is, that the order of info1, info2 etc. is not sorted and the "real data" doesn't contain a ascending number.
My first idea was to add info1, info2, info3 etc to an ArrayList.
private ArrayList<String> arr = new ArrayList<String>();
arr.add("info1");
arr.add("info2");
arr.add("info3");
Now I want to extract the substring with the method StringUtils.substringBetween() from Apache Commons (https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.4):
String result = StringUtils.substringBetween(source, arr.get(0), arr.get(1));
This works, if info1 is in the string before info2, but like I said the "real data" is not sorted.
Any idea how I can fix this?
Split those string by space and then use String's method startsWith to add the part to proper result string
Map<String, String> resultMap = new HashMap<String, String>();
String[] prefixes = new String[]{"info1", "info2", "info3"};
String source = "info1 info1ContentA info1ContentB info3 info3ContentA info3ContentB"+" info2 info2ContentA";
String[] parts = source.split(" ");
for(String part : parts) {
for(String prefix : prefixes) {
if(part.startsWith(prefix) {
String currentResult = (resultMap.containsKey(prefix) ? resultMap.get(prefix) + part + " " : part);
resultMap.put(prefix, currentResult);
}
}
}
Also consider using StringBuilder instead of adding string parts
If you cannot be sure that parts will be embraces with spaces you can change at the beginning all part to <SPACE>part in your source string using String replace method
You can use a regular expression, like this:
String source = "info1 info1ContentA info1ContentB info3 info3ContentA info3ContentB info2 info2ContentA";
for (int i = 1; i < 3; i++) {
Pattern pattern = Pattern.compile("info" + i + "Content[A-Z]");
Matcher matcher = pattern.matcher(source);
List<String> matches = new ArrayList<>();
while (matcher.find()) {
matches.add(matcher.group());
}
// process the matches list
}

Can we add list of strings to StringArray?

I have String , String str = "this is a very- good web-page";
On split of this , based on "-"
we get str[0],str[1],and str[2]
I want to assign each value of str[0] to a string array..
like below
String[] array = {"this", "is","a", "very"};
is this possible?
Thanks in advance..
Just split str[0] again on " "
You start with a string.
String str = "this is a very- good web-page";
You then split the string.
String[] strArray = str.split("-");
Here are the contents of strArray:
{"this is a very", " good web", "page"}
Note that, since strArray is an array of Strings, each element (i.e. strArray[0]) is a String. Now, you split strArray[0].
String[] strArray2 = strArray[0].split(" ");
Here are the contents of strArray2:
{"this", "is", "a", "very"}
This is the same as if you did the following:
String str2 = strArray[0];
String[] strArray2 = str2.split(" ");
String str = "this is a very- good web-page";
String[] arr=str.split("-");
Now arr[]={"this is a very","good web","page"};
String[] arr1=arr[0].split(" ");
Now arr1[]={"this","is","a","very"}
I hope you understand now.

splitting string in java using regex

How can I split following string in two strings?
input:
00:02:05,130 --> 00:02:10,130
output:
00:02:05,130
00:02:10,130
i tried this piece of code:
String[] tokens = my.split(" --> ");
System.out.println(tokens.length);
for(String s : tokens)
System.out.println(s);
but the out put is just the first part, what is wrong?
try this
String[] arr = str.split("\\s*-->\\s*");
You could use the String split():
String str = "00:02:05,130 --> 00:02:10,130";
String[] str_array = str.split(" --> ");
String stringa = str_array[0];
String stringb = str_array[1];
You may want to have a look at the following: Split Java String into Two String using delimiter

Android: split a string considering 2 separating characters

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, ":;");

Cut ':' && " " from a String with a tokenizer

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.

Categories