explode function in java as in PHP - java

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

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

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

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 \\.

Just use split and escape the regex - either by hand or using the Pattern.quote() method.

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

Related

Tokenizer java (string)

For example, Ive got Some stringa.b.c.d`, I have separated it by tokens. but now I want to do a specific thing with a, then something else with b, and something else with c. How can I do that?
String value="a.b.c.d";
StringTokenizer tokenize = new StringTokenizer(value, ".");
while(tokenize.hasMoreTokens()){
String separated1= tokenize.?????;
String separated2= tokenize.?????;
String Val1 = someMethod1(separated1);
String Val2 = someMethod2(separated2);
}
//tokenize next line is not solution
Just to spell out what #RealSkeptic already said, avoid the loop:
String value = "a.b.c.d";
String[] separated = value.split("\\.");
if (separated.length >= 2) {
String val1 = someMethod1(separated[0]);
String val2 = someMethod2(separated[1]);
} else {
// other processing here
}
You could do something similar with a StringTokenizer if you liked, only you would need at least two if statements to check whether there were enough tokens. But as #user3437460 said, StringTokenizer is now legacy; String.split() is recommended in new code.
Using String.split you can split about the . into an array.
How about something like this which will print each token:
String value = "a.b.c.d";
String[] tokens = value.split("\\.");
for (String token : tokens) {
System.out.println(token);
}
The . needs to be escaped as the split function takes a regexp and . is a wildcard
Why don't use split ? Easier to use and makes more sense here

How to split the string in java by \?

I would like to split the special character "\".
However, it doesn't seem to work out using
a.split("\");
or
a.split("\\");
While you could escape the regular expression to String.split with the somewhat surprising
String str = "a\\b\\c";
str.split("\\\\");
it is also possible to compile a Pattern with Pattern.LITERAL and then use Pattern.split(CharSequence) like
String str = "a\\b\\c";
Pattern p = Pattern.compile("\\", Pattern.LITERAL);
String[] arr = p.split(str);
System.out.println(Arrays.toString(arr));
Which outputs
[a, b, c]
This problem is solved by using
a.split("\\\\");
Simply use \n inside the string where need. No method need to split.
"\" special character in java. It is use to skip a character. Such as String s = "I am a \"Student\" of a University!";
Hear Double cote is not allow without using "\".
We can not use "\" single in a string.
String s = "I am a \ Student of a University!";
Hear "\" will make an Err.
No method need to split using "\" Simply use "\n" Where you Need.
Or use another character with it like this
String s = "Thir is a Tiger.\'I like it very nuch!\'I it a pet!";
String s2[] = s.split("\'");
for (int i = 0; i < s2.length; i++) {
System.out.println(i+" value "+s2[i]);
}
String s = "light\\hello\\text.txt";
String s3[] = s.split(Pattern.quote("\\"));
for (int i = 0; i < s3.length; i++) {
System.out.println(i+" value "+s3[i]);
}

How can I remove punctuation from input text in Java?

I am trying to get a sentence using input from the user in Java, and i need to make it lowercase and remove all punctuation. Here is my code:
String[] words = instring.split("\\s+");
for (int i = 0; i < words.length; i++) {
words[i] = words[i].toLowerCase();
}
String[] wordsout = new String[50];
Arrays.fill(wordsout,"");
int e = 0;
for (int i = 0; i < words.length; i++) {
if (words[i] != "") {
wordsout[e] = words[e];
wordsout[e] = wordsout[e].replaceAll(" ", "");
e++;
}
}
return wordsout;
I cant seem to find any way to remove all non-letter characters. I have tried using regexes and iterators with no luck. Thanks for any help.
This first removes all non-letter characters, folds to lowercase, then splits the input, doing all the work in a single line:
String[] words = instring.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");
Spaces are initially left in the input so the split will still work.
By removing the rubbish characters before splitting, you avoid having to loop through the elements.
You can use following regular expression construct
Punctuation: One of !"#$%&'()*+,-./:;<=>?#[]^_`{|}~
inputString.replaceAll("\\p{Punct}", "");
You may try this:-
Scanner scan = new Scanner(System.in);
System.out.println("Type a sentence and press enter.");
String input = scan.nextLine();
String strippedInput = input.replaceAll("\\W", "");
System.out.println("Your string: " + strippedInput);
[^\w] matches a non-word character, so the above regular expression will match and remove all non-word characters.
If you don't want to use RegEx (which seems highly unnecessary given your problem), perhaps you should try something like this:
public String modified(final String input){
final StringBuilder builder = new StringBuilder();
for(final char c : input.toCharArray())
if(Character.isLetterOrDigit(c))
builder.append(Character.isLowerCase(c) ? c : Character.toLowerCase(c));
return builder.toString();
}
It loops through the underlying char[] in the String and only appends the char if it is a letter or digit (filtering out all symbols, which I am assuming is what you are trying to accomplish) and then appends the lower case version of the char.
I don't like to use regex, so here is another simple solution.
public String removePunctuations(String s) {
String res = "";
for (Character c : s.toCharArray()) {
if(Character.isLetterOrDigit(c))
res += c;
}
return res;
}
Note: This will include both Letters and Digits
If your goal is to REMOVE punctuation, then refer to the above. If the goal is to find words, none of the above solutions does that.
INPUT: "This. and:that. with'the-other".
OUTPUT: ["This", "and", "that", "with", "the", "other"]
but what most of these "replaceAll" solutions is actually giving you is:
OUTPUT: ["This", "andthat", "withtheother"]

Java - Split string

i have string which is separated by "." when i try to split it by the dot it is not getting spitted.
Here is the exact code i have. Please let me know what could cause this not to split the string.
public class TestStringSplit {
public static void main(String[] args) {
String testStr = "[Lcom.hexgen.ro.request.CreateRequisitionRO;";
String test[] = testStr.split(".");
for (String string : test) {
System.out.println("test : " + string);
}
System.out.println("Str Length : " + test.length);
}
}
I have to separate the above string and get only the last part. in the above case it is CreateRequisitionRO not CreateRequisitionRO; please help me to get this.
You can split this string through StringTokenizer and get each word between dot
StringTokenizer tokenizer = new StringTokenizer(string, ".");
String firstToken = tokenizer.nextToken();
String secondToken = tokenizer.nextToken();
As you are finding for last word CreateRequisitionRO you can also use
String testStr = "[Lcom.hexgen.ro.request.CreateRequisitionRO;";
String yourString = testStr.substring(testStr.lastIndexOf('.')+1, testStr.length()-1);
String testStr = "[Lcom.hexgen.ro.request.CreateRequisitionRO;";
String test[] = testStr.split("\\.");
for (String string : test) {
System.out.println("test : " + string);
}
System.out.println("Str Length : " + test.length);
The "." is a regular expression wildcard you need to escape it.
Change String test[] = testStr.split("."); to String test[] = testStr.split("\\.");.
As the argument to String.split takes a regex argument, you need to escape the dot character (which means wildcard in regex):
Note that String.split takes in a regular expression, and . has special meaning in regular expression (which matches any character except for line separator), so you need to escape it:
String test[] = testStr.split("\\.");
Note that you escape the . at the level of regular expression once: \., and to specify \. in a string literal, \ needs to be escaped again. So the string to pass to String.split is "\\.".
Or another way is to specify it inside a character class, where . loses it special meaning:
String test[] = testStr.split("[.]");
You need to escape the . as it is a special character, a full list of these is available. Your split line needs to be:
String test[] = testStr.split("\\.");
Split takes a regular expression as a parameter. If you want to split by the literal ".", you need to escape the dot because that is a special character in a regular expression. Try putting 2 backslashes before your dot ("\\.") - hopefully that does what you are looking for.
String test[] = testStr.split("\\.");

Java regex to filter phone numbers

I have following example string that needs to be filtered
0173556677 (Alice), 017545454 (Bob)
This is how phone numbers are added to a text view. I want the text to look like that
0173556677;017545454
Is there a way to change the text using regular expression. How would such an expression look like? Or do you recommend an other method?
You can do as follows:
String orig = "0173556677 (Alice), 017545454 (Bob)";
String regex = " \\(.+?\\)";
String res = orig.replaceAll(regex, "").replaceAll(",", ";");
// ^remove all content in parenthesis
// ^ replace comma with semicolon
Use the expression in android.util.Patterns
Access the static variable
Patterns.PHONE
or use this expression here (Android Source Code)
Here's a resource that can guide you :
http://www.zparacha.com/validate-email-ssn-phone-number-using-java-regular-expression/
This solution works with phone numbers separated with any string that does not contain numbers:
String orig = "0173556677 (Alice), 017545454 (Bob)";
String[] numbers = orig.split("\\D+"); //split at everything that is not a digit
StringBuilder sb = new StringBuilder();
if (numbers.length > 0) {
sb.append(numbers[0]);
for (int i = 1; i < numbers.length; i++) { //concatenate all that is left
sb.append(";");
sb.append(numbers[i]);
}
}
String res = sb.toString();
or, with com.google.common.base.Joiner:
String[] numbers = orig.split("\\D+"); //split at everything that is not a digit
String res = Joiner.on(";").join(numbers);
PS. There is a minor deviation from the requirements in the best voted example, but it seems I cannot just add one character (should be replaceAll(", ", ";"), with a space after the coma, or a \\s) and I do not want to mess somebody's code.

Categories