[英]How to check if a character in a string is contained within parenthesis in JAVA?
我有一個要求,我必須從不包含在括號中的字符串中替換多次出現的字符(比如@)。 保證輸入字符串將具有有效的平衡括號。 整個字符串中可以有多對括號。
示例: String str = "今天@如何(你@正在做)@。";
用# 替換“@”符號(括號外)后預期的 output:
你今天怎么樣 #。
我可以取出括號內的字符串,進行替換並將括號文本放回去。 但我正在尋找一種更簡單、更清潔的方法。
由於您沒有提及是否可以嵌套以及字符串數據的可能大小。 這是一個可能易於理解的代碼。
如果堆棧為空 => 我們在括號外 => replaceON else OFF
public static void main(String[] args) {
String data = "How @ are (you @ do(ok@ok)ing) today @.";
char candidate = '@';
char replacement = '#';
boolean replaceFlag = true;
Stack<Character> stack = new Stack<>();
StringBuilder newData = new StringBuilder();
for(char c: data.toCharArray()) {
if (c == '(') {
stack.push(c);
replaceFlag = false;
} else if(c == ')') {
stack.pop();
}
if (stack.empty()) {
replaceFlag = true; // we are not inside parenthesis
}
if (c == candidate && replaceFlag) c = replacement;
newData.append(c);
}
System.out.println("Old data: "+ data);
System.out.println("New data: "+ newData);
}
一個簡單的方法是保持一個“for循環”來讀取字符串的所有字符,例如:
String str = "How @ are (you @ doing) today @.";
char ab ='';
for(int i=0;i<str.length();i++)
{
ab = str.charAt(i);
if(ab!='(')
// check if character is '@' and replace
else{
//print as it is;
while(ab != ')')
{//print ab as it is & increment the value of i
}
}
}
是的,這正是你需要的..
/**
*@author jore
*@version 1.0 2/1/2021
*/
public class replacer
{
public static void main(String... a)
{
/* All these yield correct outpUt */
String input = "How @ are (you @ doing) today @.";
// String input = How @ are @ ... @ ... (you @ doing (...@...)..@ ) gghhh @ today @ ( hhh @ uuu (.. @.. ) huu ( hyyy @ bhh @ ) hhh @ ) hhh @..@";
int opened_brackets = 0; //To keep track of opened brackets preventing ..(@..(@..)..#).. and allow complex nesting
char[] temp_array = input.toCharArray(); //To ease random access in input
char c; // temp char for testing
for (int i = 0; i < input.length(); i++)
{
c = temp_array[i];
if (c == '(') opened_brackets++; //record opened brackets (reason as explained above
else if (c == ')') opened_brackets--; //record closure of bracket too...
if (opened_brackets == 0 && c == '@') temp_array[i] = '#'; // Now replacing is fine if opened brackets are == 0, ot means the character is not in brackets
}
String output = new String(temp_array); //re-create edited output
System.out.println(output); //....u know what this does.....¿?
}
}
Output 1: How # are (you @ doing) today #.
Output 2: # -- replacer How # are #... #... (you @ doing (...@...)..@ ) gghhh # today hhh @ uuu (.. @.. ) huu ( hyyy @ bhh @ ) hhh @ ) hhh #..#
我創建了一個temp_array
以允許快速隨機訪問..現在我跟蹤打開的括號以防止替換嵌套括號中的@
...除了等待)
替換..如果打開0
個括號..這意味着@
放錯了位置(括號外,應立即更換...希望它能解決您的問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.