startsWith(string prefix) 需要两个字符串,并搜索两个字符串是否以相同的值开头,是否有一种方法也可以修改startsWith(string prefix) 来搜索一个字符串中重复出现的字符?
可以说
String str = "MANAMA";
我希望能够使用startsWith()和endsWith()或某种变体来搜索该字符串,以确定字符串的前缀或后缀是否相同。唯一的问题是这些方法搜索两个字符串以查看它们是否具有匹配的后缀或前缀
startsWith(string prefix) 的作用是:
String str1 = "MANAMA";
String str2 = "PANAMA.";
// Sets what characters to search for from above strings
String startStr = "MA";
// Searchs for startStr in strings
boolean starts1 = str1.startsWith(startStr);
boolean starts2 = str2.startsWith(startStr);
// Display the results of the startsWith calls.
System.out.println(starts1);
System.out.println(starts2);
endsWith(string suffix) 的作用是:
String str1 = "MANAMA";
String str2 = "PANAMA.";
// Sets what characters to search for from above strings
String endStr = "MA";
// Searchs for startStr in strings
boolean ends1 = str1.endsWith(endStr);
boolean ends2 = str2.endsWith(endStr);
// Display the results of the endsWith calls.
System.out.println(ends1);
System.out.println(ends2);
是否有一种修改方法或不同的方法能够在一个字符串内搜索,而不是在两个字符串中搜索 endStr 和 startStr?
最佳答案
不确定我是否正确理解您的问题,但您可以在同一字符串上使用 endsWith()
和 startsWith()
。例如:
String line = "MANAMA";
String edge = "MA";
boolean check = line.startsWith(edge) && line.endsWith(edge);
// returns true if the string starts and ends with "MA"
关于java - 是否可以修改startsWith(字符串前缀)来搜索一个字符串中重复出现的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9043786/