/**
*@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.....¿?
}
}
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
}
}
}
3条答案
按热度按时间yiytaume1#
是的,这正是你需要的。。
输出1:
How # are (you @ doing) today #.
输出2:# -- replacer How # are # ... # ... (you @ doing (...@...)..@ ) gghhh # today hhh @ uuu (.. @.. ) huu ( hyyy @ bhh @ ) hhh @ ) hhh #..#
我创造了一个temp_array
为了允许快速随机访问..现在我跟踪打开的支架以防止替换@
在嵌套的括号里…除了等待)
替换..如果0
支架打开。。意思是@
放错位置了(括号外,应该立即更换…希望能解决你的问题gk7wooem2#
一个简单的方法是保持一个“for循环”来读取字符串的所有字符,例如:
yrdbyhpb3#
因为您没有提到嵌套是否可行以及字符串数据的可能大小。下面是一个可能的易于理解的代码。
如果堆栈为空=>我们在括号外=>replaceon else off