Check If String Ends with One of the Strings from a List

Check if string ends with one of the strings from a list

Though not widely known, str.endswith also accepts a tuple. You don't need to loop.

>>> 'test.mp3'.endswith(('.mp3', '.avi'))
True

How to test if string ends with a list of string

How about Array.prototype.some()?

if (strings.some(s => 'hi, this is a test'.endsWith(s))) {...}

How to check if a Strings ends with any entry in a list of Strings in Java

Try this.

public static boolean checkIfFileHasExtension(String s, String[] extn) {
return Arrays.stream(extn).anyMatch(entry -> s.endsWith(entry));
}

How to use .endswith within a list of strings in Python?

Check endswith with a string and not a list. e.split() gives a list. Iterate through this list and check endswith with each item in the list.

suffix_list = []

for e in file:
for element in e.split():
if element.endswith("a"):
suffix_list.append(element)

print(len(suffix_list))

Also, a list-comprehension version:

suffix_list = [] 
for e in file:
suffix_list.extend([element for element in e.split() if element.endswith('a')])

assuming, you need a flat list rather than a list of lists.

ListString get count of all elements ending with one of strings from another list

If your fullList have some elements which have suffixes that are not present in your endings you could try something like:

    List<String> endings= Arrays.asList("AAA", "BBB", "CCC", "DDD");
List<String> fullList= Arrays.asList("111.AAA", "222.AAA", "111.BBB", "222.BBB", "111.CCC", "222.CCC", "111.DDD", "222.DDD", "111.EEE");
Function<String,String> suffix = s -> endings.stream()
.filter(e -> s.endsWith(e))
.findFirst().orElse("UnknownSuffix");
Map<String,List<String>> grouped = fullList.stream()
.collect(Collectors.groupingBy(suffix));
System.out.println(grouped);

Check if string ends with any of multiple characters

endsWith just doesn’t take multiple strings to test. You could define an array of them and check each value with endsWith:

function endsWithAny(suffixes, string) {
return suffixes.some(function (suffix) {
return string.endsWith(suffix);
});
}

function myFunction() {
var str = "Hello?";
var n = endsWithAny([".", "!", "?"], str);
document.getElementById("demo").innerHTML = n;
}

Or use a regular expression for a one-off:

var n = /[.!?]$/.test(str);


Related Topics



Leave a reply



Submit