Java String Tokens

Sort by

recency

|

1722 Discussions

|

  • + 0 comments

    // worked

    import java.util.Arrays; import java.util.Scanner;

    public class Solution {

    public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    String s = in.nextLine();
    
    String[] tokens = s.split("[ !,?._'@]+");
    tokens = Arrays.stream(tokens).filter(token -> !token.isBlank()).toArray(String[]::new);
    
    System.out.println(tokens.length);
    for (String token : tokens) System.out.println(token);
    

    } }

  • + 0 comments

    import java.util.*;

    public class Solution {

    public static void main(String[] args) { Scanner scan = new Scanner(System.in); String str = scan.nextLine(); tokens(str); } public static void tokens(String s){ s = s.trim(); String[] words = s.split("\P{L}+");

    if (s.length() == 0){
        System.out.println(0);
    }
    else{
        System.out.println(words.length);
    }
    for (String token:words){
        System.out.println(token);
    }
    

    } }

  • + 0 comments
    // Write your code here.
            String trimmed=s.trim();
            String[] tokens = trimmed.split("[ !,?._'@]+");
            int tokenCount=0;
            for(String token: tokens){
                if(!token.isEmpty()){
                    tokenCount++;
                }
            }
            System.out.println(tokenCount);
            for (String token : tokens) {
                System.out.println(token);
            }
    
  • + 0 comments

    can anybody tell me why trim() is required at all? the regex can handle the leading and trailing spaces but still when i am not using trim(), my code fails on a few test cases even after producing the exact same output as required for those cases! kinda confused

  • + 0 comments

    import java.io.; import java.util.;

    public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s = scan.nextLine();
    
        s = s.trim();
        String token[] = s.split("[ !,?._'@]+");
    
        if(s.length() == 0)
        {
            System.out.println(0);
        }else{
            System.out.println(token.length);
        }
    
        for(String tokens : token)
        {
            System.out.println(tokens);
        }
    
        scan.close();
    }
    

    }