Reputation:
I have a variable in java, which is like this I+am+good+boy
I want to get seperate them on the basis of +
, in PHP
I can use explode which is very handy, is there any function in java?I saw the split()
function definition but that was not helpful.as it take regular expression.
Any help
Thanks
Upvotes: 2
Views: 9033
Reputation: 2741
Use String.split() in regards to explode.
An example of use:
Explode :
String[] explode = "I+am+a+good+boy".split("+");
And you can reverse this like so (or "implode" it):
String implode = StringUtils.join(explode[], " ");
Upvotes: 3
Reputation: 2160
You can try like this
String str = "I+am+a+good+boy";
String[] array = str.split("\\+");
you will get "I", "am", "a", "good", "boy" strings in the array. And you can access them as
String firstElem = array[0];
In the firstElem
string you will get "I" as result.
The \\
before +
because split()
takes regular expressions (regex
) as argument and regex
has special meaning for a +
. It means one or more copies of the string trailing the +
.
So, if you want to get literal +
sign, then you have to use escape char \\
.
Upvotes: 1
Reputation: 89
You have two options as I know :
String text = "I+am+good+boy";
System.out.println("Using Tokenizer : ");
StringTokenizer tokenizer = new StringTokenizer(text, "+");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
System.out.println(" Token = " + token);
}
System.out.println("\n Using Split :");
String [] array = text.split("\\+");
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
Upvotes: 1
Reputation: 4222
String str = "I+am+a+good+boy";
String[] pieces = str.split("+")
Now you can use pieces[0]
, pieces[1]
and so on.
More Info: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String%29
Upvotes: 0
Reputation: 41208
Just use split and escape the regex - either by hand or using the Pattern.quote()
method.
Upvotes: 0