簡體   English   中英

檢查字符串是否包含給定字符

[英]Check whether a string contains given characters

我正在嘗試使用while循環檢查代碼塊是否已完成。 當字符串中不再有'+','-','*','/','('或')'的任何實例時,它將達到此狀態。 我發布的代碼是我的嘗試,盡管沒有用。

while (string.contains("+-*/()") == false)
{
modifier code
}

對於回溯和轉義稍少的解決方案:

String quoted = Pattern.quote("+-*/()");
Pattern pattern = Pattern.compile("[" + quoted + "]");
while (pattern.matcher(string).find()) {
    // modifier code
}

更好的方法是避免使Matcher陷入循環,而在修改器代碼中使用Matcher.appendReplacement()Matcher.appendTail()在一次通過StringBuffer創建結果。 但這取決於修改器代碼的作用。 (而且我仍然必須重新研究如何使用這些方法。)

您可以使用String#matches()和正則表達式,例如:

while (!string.matches(".*[-+/()*]+.*"))
{
// modifier code
}

已編輯以更正正則表達式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM