The String i want to split is " He is a very very good boy, isn't he? ". When i used only the split function the out put also printed the space after "boy," in the string. To remove that i put an if condition in the code and then the code doesn't print anything after boy .
Can someone tell me why this is happening ? Also if there is a better way to solve this problem other than using Guava .
public class Solution {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String s=scan.nextLine();
String []tokens = s.trim().split("[\\s,'?]");
int n = tokens.length;
System.out.println(n);
for(int i=0;i<tokens.length;i++)
{
if(tokens[i].charAt(0)==' ')
{
continue;
}
System.out.println(tokens[i]);
}
}
}
You're telling split
to split on a single character from that list. If you want it to split on one or more (eg, runs of those characters), add +
after it to say "one or more of the thing before":
String []tokens = s.trim().split("[\\s,'?]+");
// Here ----------------------------------^
(FWIW, including '
on the list of characters to split on seems a bit odd, but we don't know your use case, so...)
check this solution.
String str="He is a very very good boy, isn't he?";
String[] Val = str.split("[' ,@!_.?]+");
System.out.println(Val.length);
for(String token :Val) {
System.out.println(token);}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.