java - Tracking brackets in a string -
i having next string , want track closing bracket of round( ) in string.
"=round(if(and($by18=2);ca18*cb18/$m$11;if($by18=3;ca18*cb18/$m$10;if($by18=4;round(ca18*cb18;$m$10)/$m$9;ca18*cb18)))/$m$12;$m$11)";
public class roundparser { public static string parseround(string text) { text = text.touppercase(); string result; char[] ch = text.tochararray(); int count = -1; string temp = ""; (int = 0; < ch.length; i++) { temp = temp + ch[i]; system.out.println(count); if ("round(".equals(temp)) { count++; } if ("(".equals(temp)) { count++; } if (")".equals(temp) && count > 0) { count--; } if (")".equals(temp) && count == 0) { ch[i] = '#'; } if (!"round(".startswith(temp) || temp.length() > 5) { temp = ""; } } text = string.valueof(ch); result = text; homecoming result; } public static void main(string[] args) { string text = "=round(if(and($by18=2);ca18*cb18/$m$11;if($by18=3;ca18*cb18/$m$10;if($by18=4;round(ca18*cb18;$m$10)/$m$9;ca18*cb18)))/$m$12;$m$11)"; system.out.println(parseround(text)); } } however, using parser @ moment getting:
=round(if(and($by18=2);ca18*cb18/$m$11;if($by18=3;ca18*cb18/$m$10;if($by18=4;round(ca18*cb18;$m$10)/$m$9;ca18*cb18))#/$m$12;$m$11#
the output want is:
=round(if(and($by18=2);ca18*cb18/$m$11;if($by18=3;ca18*cb18/$m$10;if($by18=4;round(ca18*cb18;$m$10#/$m$9;ca18*cb18)))/$m$12;$m$11#
as can see not right ) replaced, ;$m$11)"; , ;$m$10). appreciate if have thought how repalce these 2 cases.
there 2 approaches this
1) if number of opening , closing brackets going equal, can track lastly closing bracket using loop.
2) if not sure opening , closing brackets equal, can following-->
public class roundparser { public static string parseround(string text) { text = text.touppercase(); string result; char[] ch = text.tochararray(); int count=0,pos=0; int c[10]; for(int i=0;i<ch.length;i++){ if(ch[i].equals("(")){ count++; if(ch[i-1].equals("d")){ c[pos]=count; //will store count value @ every opening round pos++; } } if(ch[i].equals(")")){ count--; for(int j=0;j<10;j++){ if(c[j]==count) //if closing of round had been encountered ch[i]="#"; } } } text = string.valueof(ch); result = text; homecoming result; } public static void main(string[] args) { string text = "=round(if(and($by18=2);ca18*cb18/$m$11;if($by18=3;ca18*cb18/$m$10;if($by18=4;round(ca18*cb18;$m$10)/$m$9;ca18*cb18)))/$m$12;$m$11)"; system.out.println(parseround(text)); } } there go.
i think should work.
hope helps.
java string algorithm
No comments:
Post a Comment