How to tokenize brackets? - java

I have used StringTokenizer as follows and expected it to actually separates each brackers but it took all as a token. How can I tokenize them?
Stack<String> a=new Stack<>();
String S = "{[()()]}";
String temp="";
StringTokenizer str=new StringTokenizer(S);
while (str.hasMoreTokens()){
temp=str.nextToken();
a.push(temp);
}

// write all symbols you want here on st
StringTokenizer st = new StringTokenizer(str, "#!");
String s = "Hello, i am using Stack Overflow;";
System.out.println("s = " + s);
String delims = " ,;";
StringTokenizer tokens = new StringTokenizer(s, delims);
while(tokens.hasMoreTokens())
System.out.println(tokens.nextToken());

If you try
StringTokenizer st = new StringTokenizer("[[]{}[[]]()]","[]{}()");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
It will return empty as it is tokenizing the string but there is nothing else left after tokenising all the brackets. If you instead try :
StringTokenizer st = new StringTokenizer("[[a]{b}[[c]d]()]","[]{}()");
You will get a b c d - the tokenised values.
Now if you want to leave the brackets there, id recommend lookahead and lookback regex :
StringTokenizer st = new StringTokenizer(z,"[]{}()");
String regEx "(?<=[{}()\\[\\]])|(?=[{}()\\[\\]])";
System.out.println(Arrays.toString(z.split();
that will return :
[[, [, a, ], {, b, }, [, [, c, ], d, ], (, ), ]]

Related

How to convert char to String in tokenizer in Java

Trying to read a file separated by commas into an array and not sure how to make party into a string to work with tokenizer
for(int i = 0; i < s.length; i++) {
String str = scan.nextLine();
StringTokenizer st = new StringTokenizer(str, ",");
//String [] tokens = str.split(",");
String name = st.nextToken();
String abbreviation = st.nextToken();
long population = Long.parseLong(st.nextToken());
String govName = st.nextToken();
char party = st.nextToken();
int ageWhenElected = Integer.parseInt(st.nextToken());
s[i] = new State(name, abbreviation, population, govName ,party, ageWhenElected);
Try
char party = st.nextToken().charAt(0);
You can join your array of string with comma as separator
StringUtils.join(strArray, ",");

How can i split String in java with custom pattern

I am trying to get the location data from this string using String.split("[,\\:]");
String location = "$,lat:27.980194,lng:46.090199,speed:0.48,fix:1,sats:6,";
String[] str = location.split("[,\\:]");
How can i get the data like this.
str[0] = 27.980194
str[1] = 46.090199
str[2] = 0.48
str[3] = 1
str[4] = 6
Thank you for any help!
If you just want to keep the numbers (including dot separator), you can use:
String[] str = location.split("[^\\d\\.]+");
You will need to ignore the first element in the array which is an empty string.
That will only work if the data names don't contain numbers or dots.
String location = "$,lat:27.980194,lng:46.090199,speed:0.48,fix:1,sats:6,";
Matcher m = Pattern.compile( "\\d+\\.*\\d*" ).matcher(location);
List<String> allMatches = new ArrayList<>();
while (m.find( )) {
allMatches.add(m.group());
}
System.out.println(allMatches);
Quick and Dirty:
String location = "$,lat:27.980194,lng:46.090199,speed:0.48,fix:1,sats:6,";
List<String> strList = (List) Arrays.asList( location.split("[,\\:]"));
String[] str = new String[5];
int count=0;
for(String s : strList){
try {
Double d =Double.parseDouble(s);
str[count] = d.toString();
System.out.println("In String Array:"+str[count]);
count++;
} catch (NumberFormatException e) {
System.out.println("s:"+s);
}
}

String reverse using Java'sstringbuilder

I develop using Java to make a little project.
I want String reverse.
If I entered "I am a girl", Printed reversing...
Already I tried to use StringBuilder.
Also I write it using StringBuffer grammar...
But I failed...
It is not printed my wish...
WISH
My with Print -> "I ma a lrig"
"I am a girl" -> "I ma a lrig" REVERSE!!
How can I do?..
Please help me thank you~!!!
public String reverse() {
String[] words = str.split("\\s");
StringTokenizer stringTokenizer = new StringTokenizer(str, " ");
for (String string : words) {
System.out.print(string);
}
String a = Arrays.toString(words);
StringBuilder builder = new StringBuilder(a);
System.out.println(words[0]);
for (String st : words){
System.out.print(st);
}
return "";
}
Java 8 code to do this :
public static void main(String[] args) {
String str = "I am a girl";
StringBuilder sb = new StringBuilder();
// split() returns an array of Strings, for each string, append it to a StringBuilder by adding a space.
Arrays.asList(str.split("\\s+")).stream().forEach(s -> {
sb.append(new StringBuilder(s).reverse() + " ");
});
String reversed = sb.toString().trim(); // remove trailing space
System.out.println(reversed);
}
O/P :
I ma a lrig
if you do not want to go with lambda then you can try this solution too
String str = "I am a girl";
String finalString = "";
String s[] = str.split(" ");
for (String st : s) {
finalString += new StringBuilder(st).reverse().append(" ").toString();
}
System.out.println(finalString.trim());
}

How to split multiple operator in string in java

I have string in java but not understand how to split these type of string using.
I have only arithmetic and logical operator .
char[] operators = new char[] { '\\', 'x', '+', '-', '>', '*','<', '=' };
String str_spit="usa_newyork=japan\london*44+jhon<last-987";
Actual String - >
String a= QN_770_0=QN_770_0\10
and
String b= QN_770_0>66
My Code:
ArrayList <String> logics;
ArrayList <String> logicQuestions = null;
char[] operators = new char[] { '\\', 'x', '+', '-', '>', '<', '=' };
String str_spit="QN_770_0=QN_770_0\10";
for ( jj = 0; jj < operators.length; jj++)
{
System.out.println("operators.toString()---->"+operators[jj]);
//String[] questions = logicText.split(operators);
String s = "" + operators[jj];
String[] questions=str_spit.split(s);
System.out.println("questions questions---->"+questions);
//for each segment, save all question codes.
for (int j = 0; j < questions.length; j++)
{
String question = questions[j];
System.out.println("questions questions---question->"+questions);
if (question.startsWith("QN_") && !logicQuestions.contains(question))
logicQuestions.add(question);
System.out.println("logicQuestions---logicQuestions->"+logicQuestions);
}
}
Error:
operators.toString()---->\
Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
^
Try using StringTokenizer
String delim = new String(operators);
StringTokenizer st = new StringTokenizer(str_spit, delim);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
I would use the Javascript engine to do this. It will not only parse the String but evalate it for you and much, much more.
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");
ScriptContext context = new SimpleScriptContext();
int scope = context.getScopes().get(0);
context.setAttribute("japan", 100, scope);
context.setAttribute("london", 10, scope);
context.setAttribute("jhon", -10, scope);
context.setAttribute("last", 1000, scope);
String str = "usa_newyork= japan / london * 44 + jhon < last - 987";
Object usa_newyork = engine.eval(str, context);
System.out.println(usa_newyork);
prints
false

String Tokenizer separation

I want to know how can we separate words of a sentence where delimiter is be a ' '(space) or '?'
or '.'.
For ex
Input: THIS IS A STRING PROGRAM.IS THIS EASY?YES,IT IS.
Output:
THIS
IS
A
STRING
PROGRAM
IS
THIS
EASY
YES
IT
IS
Refer to the constructor of the StringTokenizer class in Java. It has provision to accept custom delimiter.
Try this:
StringTokenizer tokenizer = new StringTokenizer("THIS IS A STRING PROGRAM.IS THIS EASY?YES,IT IS", " .?");
while (tokenizer.hasMoreElements()) {
System.out.println(tokenizer.nextElement());
}
public static void main(String[] args) {
String str = "THIS IS A STRING PROGRAM.IS THIS EASY?YES,IT IS";
StringTokenizer st = new StringTokenizer(str);
System.out.println("---- Split by space ------");
while (st.hasMoreElements()) {
System.out.println(st.nextElement());
}
System.out.println("---- Split by comma ',' ------");
StringTokenizer st2 = new StringTokenizer(str, ",");
while (st2.hasMoreElements()) {
System.out.println(st2.nextElement());
}
}

Categories