I have an array I want to check the the last digits if it is in the array.
Example:
String[] types = {".png",".jpg",".gif"}
String image = "beauty.jpg";
// Note that this is wrong. The parameter required is a string not an array.
Boolean true = image.endswith(types);
Please note:
I know I can check each individual item using a for loop.
I want to know if there is a more efficient way of doing this. Reason being is that image string is already on a loop on a constant change.
Arrays.asList(types).contains(image.substring(image.lastIndexOf('.') + 1))
You can substring the last 4 characters:
String ext = image.substring(image.length - 4, image.length);
and then use a HashMap or some other search implementation to see if it is in your list of approved file extensions.
if(fileExtensionMap.containsKey(ext)) {
Use Arrays.asList to convert to a List. Then you can check for membership.
String[] types = {".png",".jpg",".gif"};
String image = "beauty.jpg";
if (image.contains("."))
System.out.println(Arrays.asList(types).contains(
image.substring(image.lastIndexOf('.'), image.length())));
Related
When I concatenate two strings (e.g. "q5q3q2q1" and "q5q4q3q2q1") I get string that have duplicate substrings q5,q3,q2,q1 which appears twice.
The resultant string would be "q5q3q2q1q5q4q3q2q1" and I need to have each substring (q[number]) appear once i.e."q5q4q3q2q1".
Substring doesn't have to start with 'q', but I could set restriction that it doesn't start with number, also it could have multiple numbers like q11.
What could I use to get this string? If solution could be written in Java that would be good, otherwise only algorithm would be useful.
You can split the concatenated string in groups and then use a set, if order of groups doesn't matter, or a dictionary if it is.
a = "q5q3q2q1"
b = "q5q4q3q2q1"
# Concatenate strings
c = a + b
print(c)
# Create the groups
d = ["q" + item for item in c.split("q") if item != ""]
print(d)
# If order does not matter
print("".join(set(d)))
# If order does matter
print("".join({key: 1 for key in d}.keys()))
Another solution, this one is using regular expression. Concatenate the string and find all patterns ([^\d]+\d+) (regex101). Then add found strings to set to remove duplicates and join them:
import re
s1 = "q5q3q2q1"
s2 = "q5q4q3q2q1"
out = "".join(set(re.findall(r"([^\d]+\d+)", s1 + s2)))
print(out)
Prints:
q5q2q1q4q3
Some quick way of doing this via java as you asked in question:
String a = "q1q2q3";
String b = "q1q2q3q4q5q11";
List l1 = Arrays.asList(a.split("q"));
List l2 = Arrays.asList(b.split("q"));
List l3 = new ArrayList<String>();
l3.addAll(l1);
List l4 = new ArrayList<String>();
l4.addAll(l2);
l4.removeAll(l3);
l3.addAll(l4);
System.out.println(String.join("q", l3));
Output:
q1q2q3q4q5q11
This is a variation of #DanConstantinescu's solution in JS:
Start with the concatenated string.
Split string at the beginning of a substring composed of text followed by a number. This is implemented as a regex lookahead, so split returns the string portions as an array.
Build a set from this array. The constructor performs deduplication.
Turn the set into an array again
Concat the elements with the empty string.
While this code is not Java it should be straightforward to port the idea to other (imperative or object-oriented) languages.
let s_concatenated = "q5q3q2q1" + "q5q4q3q2q1" + "q11a13b4q11"
, s_dedup
;
s_dedup =
Array.from(
new Set(s_concatenated
.split(/(?=[^\d]+\d+)/) // Split into an array
) // Build a set, deduplicating
) // Turn the set into an array again
.join('') // Concat the elements with the empty string.
;
console.log(`'${s_concatenated}' -> '${s_dedup}'.`);
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.
I have written a function that checks if a string contains certain words but am not happy with the way the code looks
SO currently i have
private String url = "validator=http://url.com;useraccount=sf4cdamloci;licence=39I8934U401;addedon=343443334;serial=7QW0-5TU8-YN9P-G4FZ;limit=123;days=10"
private String musthave ="validator,useraccount,licence,addedon,serial,limit,days"
So i wanted to check that the url contains the must have words in the string. That eg url must have validator, useraccount, licence.....
SO i have tried the following
Boolean has_validator = false;
Boolean has_licence = false;
.....//others with has_ prefix
String[] split_url = url.split(";")
for(String key_item : split_url){
String[] splitteditem = key_item.split("=");
if (splitteditem[0].equalsIgnoreCase("validator")){
has_validator = true;
}
if (splitteditem[0].equalsIgnoreCase("useraccount")){
has_useraccount = true;
}
....others as well
}
Then later i can easily check
if(has_useraccount && has_...)
The above solution works buts its not scalable as whenever i include a new must have ill have to edit my function.
Is there a better way to achieve this. Am still new to java. I have checked on regex but still i can figure our on how to achieve this.
How do i proceed
Don't use a String to represent a set of Strings. Use... a Set of String: Set<String>. Or at least an array of strings.
Then just use a loop. If any of the word in the set isn't contain in the text, you can immediately return false. If you have never returned false in the loop, then all the words are contained in the text, and you can return true.
Pseudo code:
for each word in the set
if the word is not in the text, return false
end for
return true
If you have a Collection of must-have strings, then you can do something simple like:
mustHave.stream().allMatch(url::contains)
My example isn't doing a case-insensitive check, but you get the idea.
This is my Result where i got response from server that I want to get by Soap.I can parse this value by JSON but I'm having a problem doing so as I wish to get this value split.
Result=1~Saved successfully~{ "TABLE":[{ "ROW":[ { "COL":{ "UserID":"30068"}} ]}]}
I am using this code to get UserId values in tmpVal, however am not obtaining my desired results.
String tmpVal = returnValue.toString().split("~")[3];
String tmpVal = returnValue.toString().split("~")[3];
This would give you the 4th String in the array produced by split, but since split only produced an array of 3 Strings, this code gives you an exception.
If you want to get the last part of the split response - { "TABLE":[{ "ROW":[ { "COL":{ "UserID":"30068"}} ]}]} - you need returnValue.toString().split("~")[2].
Of course, it would be safer to first test how many Strings were returned by split :
String[] splitResult = returnValue.toString().split("~");
if (splitResult.length > 2) {
tempVal = splitResult[2];
}
As stated above in the comment section, Arrays start with index 0, thus if you have an array with 3 elements, the index are 0..1..2 and not 1..2..3
All you have to do is change the String tmpVal = returnValue.toString().split("~")[3]; to:
String tmpVal = returnValue.toString().split("~")[2];
As that will obtain the 3rd element instead of the fourth element as you've been trying to do.
You may also check out this question
So I'm looking to get the first numbers of an IP. Let's say I have something like 255.35.54.34. I want to get the first part of numbers up until the first period. How would I do this in Java? So it'd leave me with 255.
Take a look at the String class. You can use a couple of methods to accomplish this:
the indexof(...) method will give you the offset of the "."
the substring(...) method will allow you to get a string using the above offset
Or another option is to use the split(...) method to get an array of all four IP values.
As #camickr says, you can use indexOf and substring thus:
String ipAddress = "192.168.1.9";
System.out.println(ipAddress.substring(0, ipAddress.indexOf('.')));
This will print "192"
You can use the split() method with a period as the argument. This will split the string along periods and give you a String[].
Then get the values just as you would from a normal array by using a subscript. In your case index 0 will get you the value
String ip = "255.255.255.255";
String[] splitIP = ip.split(".");
String required = splitIP[0];
You can do it in two ways :
One is that you use String.split() method, and other is to using StringTokenizer class.
Using String.split() :
String ip = "255.1.2.3";
String[] splitIP = ip.split("\\.");
String required = splitIP[0];
System.out.println(required);
Here \\ is required,oherwise it will throw an exception
Using StringTokenizer :
String ip = "255.1.2.3";
StringTokenizer tk=new StringTokenizer(ip,".");
while (tk.hasMoreTokens())
{
System.out.println(tk.nextToken());
break;
}
Hope this will help you..