Java Split String Using Delimiter [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Matching a “.” in java
I have a String 1.2.4 which i want to split and get 2 to compare it with another String that i get.
I am trying to do the following
StringTokenizer old_ver = new StringTokenizer(oldVersion, ".");
int oldVer = Integer.parseInt(old_ver.nextToken());
oldVer = Integer.parseInt(old_ver.nextToken());
StringTokenizer new_ver = new StringTokenizer(newVersion, ".");
int newVer = Integer.parseInt(new_ver.nextToken());
newVer = Integer.parseInt(new_ver.nextToken());
if (oldVer == newVer) {
return true;
}
IS there a better way to do it using .Split()

The problemis that in Regex "." is a single character. Hence, you need to escape it using "\\."
Similarly, you can use
string.split("\\.");
EDIT:
split() method of the String class uses Pattern and Matcher internally which is normally the API used for Regex in Java.
So there is no problem going with split.

In your code, 1.2.1 would be "compatible" with 3.2.0, and this looks like a serious problem, regardless if you use String.split or not. Also, you do not need to parse version numbers into integers as you only compare for equality.
StringTokenizer old_ver = new StringTokenizer(oldVersion, ".");
StringTokenizer new_ver = new StringTokenizer(newVersion, ".");
return (old_ver.nextToken().equals(new_ver.nextToken() &&
old_ver.nextToken().equals(new_ver.nextToken() );
You can surely do with String.split as well:
String [] oldV = String.split(oldVersion,"\\.");
String [] newV = String.split(newVersion,"\\.");
return oldV[0].equals(newV[0]) && oldV[1].equals(newV[1]);
The String.split() version seems slightly shorter but but for me it looks slightly more difficult to read because:
It involves additional thinking step that dot (.) is a reserved char and must be escaped.
"Next element and then following element" seems involving less thinking effort than "element at position 0 and then element at position 1".
It may pay to have some version comparator that first compares major, then intermediate and then minor parts of the version number the way that we could have the tests like "1.2.4 or later".

Related

How to check any of the list of words present in the string?

I have list of words which i need to check if any of the words in list is present in string or not but word in the string can be in any format let say i have list of words {:carloan:,creditcard} but in string it can be like car-loan or carloan or :carloan in any of this formats.
I am using lambda function in java to find the any near match but its not working like below:
List<String> list = new ArrayList<>();
list.add(":carloan:")
list.add(":creditcard:")
String inputString = "i want carloan"
boolean match = list.stream().anyMatch(s -> inputString.contains(s));
But above method is giving boolean true only if the substring is matching exactly same with the word in the list.
Is there way i can give true even if it match partially let say the user entered car-loan but in list it's like :carloan: i don't want to use iterate over a list and do matching. Please suggest me way i can do using lambda function in java.
You could use a regex approach here:
List<String> list = new ArrayList<>();
list.add("carloan");
list.add("creditcard");
String regex = ".*(?:" + String.join("|", list) + ").*";
String input = "I am looking for a carloan or creditcard";
if (input.matches(regex)) {
System.out.println("MATCH");
}
Some possible changes you might want to make to the above would be to add word boundaries around the alternation. That is, you might want to use this regex pattern:
.*\b(?:carloan|creditcard)\b.*
This would avoid matching e.g. carloans when you really want to exactly match only the singular carloan.
Edit:
Here is a version using regex closer to your original starting point:
boolean result = list.stream().anyMatch(s -> input.matches(".*\\b" + s + "\\b.*"));
if (result) {
System.out.println("MATCH");
}
We can stream your list of terms, and then assert whether the input string matches any term using regex. But note that this approach means calling String#matches N times, for a list of N terms, while the above approach just makes a single call to that API. I would bet on the alternation approach being more efficient here.

Deleting content of every string after first empty space

How can I delete everything after first empty space in a string which user selects? I was reading this how to remove some words from a string in java. Can this help me in my case?
You can use replaceAll with a regex \s.* which match every thing after space:
String str = "Hello java word!";
str = str.replaceAll("\\s.*", "");
output
Hello
regex demo
Like #Coffeehouse Coder mention in comment, This solution will replace every thing if the input start with space, so if you want to avoid this case, you can trim your input using string.trim() so it can remove the spaces in start and in end.
Assuming that there is no space in the beginning of the string.
Follow these steps-
Split the string at space. It will create an array.
Get the first element of that array.
Hope this helps.
str = "Example string"
String[] _arr = str.split("\\s");
String word = _arr[0];
You need to consider multiple white spaces and space in the beginning before considering the above code.
I am not native to JAVA Programming but have an idea that it has split function for string.
And the reference you cited in the question is bit complex, while you can achieve the desired thing very easily.
P.S. In future if you make a mind to get two words or three, splitting method is better (assuming you have already dealt with multiple white-spaces) else substring is better.
A simple way to do it can be:
System.out.println("Hello world!".split(" ")[0]);
// Taking 'str' as your string
// To remove the first space(s) of the string,
str = str.trim();
int index = str.indexOf(" ");
String word = str.substring(0, index);
This is just one method of many.
str = str.replaceAll("\\s+", " "); // This replaces one or more spaces with one space
String[] words = str.split("\\s");
String first = words[0];
The simplest solution in my opinion would be to just locate the index which the user wants it to be cut off at and then call the substring() method from 0 to the index they wanted. Set that = to a new string and you have the string they want.
If you want to replace the string then just set the original string = to the result of the substring() method.
Link to substring() method: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)
There are already 5 perfectly good answers, so let me add a sixth one. Variety is the spice of life!
private static final Pattern FIRST_WORD = Pattern.compile("\\S+");
public static String firstWord(CharSequence text) {
Matcher m = FIRST_WORD.matcher(text);
return m.find() ? m.group() : "";
}
Advantages over the .split(...)[0]-type answers:
It directly does exactly what is being asked, i.e. "Find the first sequence of non-space characters." So the self-documentation is more explicit.
It is more efficient when called on multiple strings (e.g. for batch processing a large list of strings) because the regular expression is compiled only once.
It is more space-efficient because it avoids unnecessarily creating a whole array with references to each word when we only need the first.
It works without having to trim the string.
(I know this is probably too late to be of any use to the OP but I'm leaving it here as an alternative solution for future readers.)
This would be more efficient
String str = "Hello world!";
int spaceInd = str.indexOf(' ');
if(spaceInd != -1) {
str = str.substring(0, spaceInd);
}
System.out.println(String.format("[%s]", str));

How to find a String of last 2 items in colon separated string

I have a string = ab:cd:ef:gh. On this input, I want to return the string ef:gh (third colon intact).
The string apple:orange:cat:dog should return cat:dog (there's always 4 items and 3 colons).
I could have a loop that counts colons and makes a string of characters after the second colon, but I was wondering if there exists some easier way to solve it.
You can use the split() method for your string.
String example = "ab:cd:ef:gh";
String[] parts = example.split(":");
System.out.println(parts[parts.length-2] + ":" + parts[parts.length-1]);
String example = "ab:cd:ef:gh";
String[] parts = example.split(":",3); // create at most 3 Array entries
System.out.println(parts[2]);
The split function might be what you're looking for here. Use the colon, like in the documentation as your delimiter. You can then obtain the last two indexes, like in an array.
Yes, there is easier way.
First, is by using method split from String class:
String txt= "ab:cd:ef:gh";
String[] arr = example.split(":");
System.out.println(arr[arr.length-2] + " " + arr[arr.length-1]);
and the second, is to use Matcher class.
Use overloaded version of lastIndexOf(), which takes the starting index as 2nd parameter:
str.substring(a.lastIndexOf(":", a.lastIndexOf(":") - 1) + 1)
Another solution would be using a Pattern to match your input, something like [^:]+:[^:]+$. Using a pattern would probably be easier to maintain as you can easily change it to handle for example other separators, without changing the rest of the method.
Using a pattern is also likely be more efficient than String.split() as the latter is also converting its parameter to a Pattern internally, but it does more than what you actually need.
This would give something like this:
String example = "ab:cd:ef:gh";
Pattern regex = Pattern.compile("[^:]+:[^:]+$");
final Matcher matcher = regex.matcher(example);
if (matcher.find()) {
// extract the matching group, which is what we are looking for
System.out.println(matcher.group()); // prints ef:gh
} else {
// handle invalid input
System.out.println("no match");
}
Note that you would typically extract regex as a reusable constant to avoid compiling the pattern every time. Using a constant would also make the pattern easier to change without looking at the actual code.

Best way to trim exactly one quote from each side of Java string

I want to be able to trim one quote from each side of a java string. Here are some examples.
"foo" -> foo
"foo\"" -> foo\"
"\"foo\"" -> \"foo\"
I'm currently using StringUtils.trim from common lang but when I end the string with a escaped quote, it trims that too because they are consecutive. I want to be able to trim exactly one quote.
I ended up using org.apache.commons.lang3.StringUtils.substringBetween and it works.
You may also use the substring() method and trim the first and last characters on condition although it's a bit long.
trimedString= s.substring((s.charAt(0)=='"')?1:0 , (s.charAt(s.length()-1)=='"')?s.length()-1:s.length());
I prefer to use this String method
public String[] split(String regex)
basically if you feed in the quotation mark then you will get an array of strings holding all of the chunks between your quotation marks.
String[] parts = originalString.split("\"");
String quoteReduced = parts[0];
for (int i = 1; i < (parts.length() -1); i++){
quoteReduced = quoteReduced.concat( parts[i] +"\"" );
}
quoteReduced = quoteReduced.concat( "\"" +parts[parts.length()-1]);
While it may not be the most straight forward it is the way that I would get around this. The first piece and last piece could be included in the loop but would require an if statement.

replaceAll does not replace string [duplicate]

This question already has answers here:
String replace method is not replacing characters
(5 answers)
Closed 7 years ago.
I want the text "REPLACEME" to be replaced with my StringBuffer symbols. When I print symbols, it is a valid string. When I print my query, it still has the text REPLACEME instead of symbols. Why?
private String buildQuery(){
String query = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(REPLACEME)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
deserializeQuotes();
StringBuffer symbols = new StringBuffer();
for(int i = 0; i < quotes.size();i++){
if(i == (quotes.size()-1))
symbols.append("%22" + quotes.get(i).getSymbol() + "%22%"); //end with a quote
else
symbols.append("%22" + quotes.get(i).getSymbol() + "%22%2C");
}
System.out.println("***SYMBOLS***" + symbols.toString());
query.replaceAll("REPLACEME", symbols.toString());
return query;
}
Change
query.replaceAll("REPLACEME", symbols.toString());
to:
query = query.replaceAll("REPLACEME", symbols.toString());
Strings in Java are designed to be immutable.
That is why replaceAll() can't replace the characters in the current string, so it must return a new string with the characters replaced.
Also if you want to simply replace literals and don't need regex syntax support use replace instead of replaceAll (regex syntax support is only difference between these two methods). It is safer in case you would want to replace literals which can contain regex metacharacters like *, +, [, ] and others.
Read the documentation :) replaceAll() returns a new String, it does replace inside the existing String. The reason for that is that Strings are immutable objects.
The String object in Java is immutable. The replaceAll will not replace the data in the string, it will generate a new string. Try this:
query = query.replaceAll("REPLACEME", symbols.toString());

Categories

Resources