Java String Tokens

Sort by

recency

|

1796 Discussions

|

  • + 0 comments

    It’s a good exercise for understanding how to break down a sentence into meaningful parts, especially by defining tokens as sequences of alphabetic characters only. Khelo24bat

  • + 0 comments

    If your test cases are failing due to edge cases:

    1. Add a condition like s.trim().length == 0 to check whether the string is empty. If it is, print 0 and return.
    2. Use s.trim().split() to remove any leading or trailing spaces before processing the string.
  • + 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();
        // Write your code here.
                // Split on any non-alphabetic character
        String[] tokens = s.trim().split("[^A-Za-z]+");
    
        // Handle empty input case
        if (s.trim().isEmpty()) {
            System.out.println(0);
            return;
        }
    
        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 sc = new Scanner(System.in);
            String s = sc.nextLine();
            
            // Split on any non-alphabetic character
            String[] tokens = s.trim().split("[^A-Za-z]+");
            
            // Handle empty input case
            if (s.trim().isEmpty()) {
                System.out.println(0);
                return;
            }
            
            System.out.println(tokens.length);
            for (String token : tokens) {
                System.out.println(token);
            }
        }
    }
    
  • + 0 comments

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

    public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String statement = scan.nextLine();
        scan.close();
    
        String cleaned = statement.replaceAll("[^a-zA-Z\\s]", " ");
    
        String[] words = cleaned.split("\\s+");
    
        System.out.println(words.length);
    
        for(String word : words){
            System.out.println(word);
        }
    
    
    }
    

    }