如何用C#判断字符串是否以List<string>中任意元素开头?
检查字符串列表中是否存在目标字符串的前缀元素
给定字符串列表:
['xxx', 'xxxyy', 'ccccy']
和目标字符串:
String example1 = "xxxyyy";
需求是判断列表中是否存在任意字符串是example1的开头,只需返回布尔结果,无需定位具体匹配项。
Python 实现
利用any()函数结合字符串的startswith()方法,一行代码即可完成判断,且效率较高(找到匹配项即停止遍历):
str_list = ['xxx', 'xxxyy', 'ccccy'] example1 = "xxxyyy" has_matching_prefix = any(example1.startswith(s) for s in str_list) print(has_matching_prefix) # 输出: True
Java 实现
提供两种常见写法,均能高效完成判断:
普通循环写法
import java.util.List; public class PrefixChecker { public static void main(String[] args) { List<String> strList = List.of("xxx", "xxxyy", "ccccy"); String example1 = "xxxyyy"; boolean hasMatchingPrefix = false; for (String s : strList) { if (example1.startsWith(s)) { hasMatchingPrefix = true; break; // 找到匹配立即终止循环 } } System.out.println(hasMatchingPrefix); // 输出: true } }
Stream API 写法
import java.util.List; public class PrefixChecker { public static void main(String[] args) { List<String> strList = List.of("xxx", "xxxyy", "ccccy"); String example1 = "xxxyyy"; boolean hasMatchingPrefix = strList.stream() .anyMatch(s -> example1.startsWith(s)); System.out.println(hasMatchingPrefix); // 输出: true } }
anyMatch()方法会在找到第一个匹配项时停止流处理,性能与循环写法一致,但代码更简洁。
内容的提问来源于stack exchange,提问作者Mark Wekking
相关产品推荐
相关产品推荐

