在Java中,要檢測一個字符串是否是包含URL的回文文本,你可以按照以下步驟操作:
以下是一個示例代碼:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PalindromeWithURL {
public static void main(String[] args) {
String input = "A man, a plan, a canal: Panama. https://example.com";
System.out.println(isPalindromeWithURL(input));
}
public static boolean isPalindromeWithURL(String input) {
// 將字符串轉換為小寫
input = input.toLowerCase();
// 使用正則表達式提取URL
String urlPattern = "(https?://\\S+)";
Pattern pattern = Pattern.compile(urlPattern);
Matcher matcher = pattern.matcher(input);
// 將提取到的URL從原始字符串中移除
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "");
}
matcher.appendTail(sb);
String stringWithoutURL = sb.toString();
// 檢查處理后的字符串是否是回文
int left = 0;
int right = stringWithoutURL.length() - 1;
while (left < right) {
if (stringWithoutURL.charAt(left++) != stringWithoutURL.charAt(right--)) {
return false;
}
}
return true;
}
}
這個示例代碼首先將輸入字符串轉換為小寫,然后使用正則表達式提取URL并將其從原始字符串中移除。最后,它檢查處理后的字符串是否是回文。在這個例子中,輸入字符串 “A man, a plan, a canal: Panama. https://example.com” 被識別為包含URL的回文文本。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。