We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Java
- Strings
- Java String Tokens
- Discussions
Java String Tokens
Java String Tokens
+ 0 comments Scanner scan = new Scanner(System.in); String s = scan.nextLine(); // Write your code here. scan.close(); s = s.trim(); if (s.isEmpty()) { System.out.println(0); return; } String[] strs = s.split("[^A-Za-z0-9]+"); System.out.println(strs.length); for (String string : strs) { System.out.println(string); }
+ 0 comments Scanner scan = new Scanner(System.in); String s = scan.nextLine().trim(); if (s.isEmpty()) { System.out.println("0"); } else { String[] toReplace = {" ", ",", "'", "?", "@", "!", "[", "]", "-", "_", "+", "."}; for (String toCarry: toReplace) { if (s.contains(toCarry)) { s = s.replace(toCarry, " "); } } String[] sArray = s.split(" "); ArrayList<String> sArrayList = new ArrayList<>(); for (String sArray1: sArray) { sArrayList.add(sArray1); } for (int i=0; i<sArrayList.size(); i++) { while (sArrayList.get(i).isEmpty()) { sArrayList.remove(i); } } System.out.println(sArrayList.size()); for (String sArray3: sArrayList) { System.out.println(sArray3); } } scan.close();
+ 0 comments Scanner scan = new Scanner(System.in); String s = scan.nextLine().trim(); if (!s.isEmpty()) { String[] sArray = s.split("[^A-Za-z0-9]+"); System.out.println(sArray.length); for (String temp: sArray) { System.out.println(temp); } } else { System.out.println("0"); } scan.close();
+ 0 comments why is the string.trim method used in this question i have tried running the code with the same test cases as custom input that failed without using the method and the result is exactly the same. Can anyone please explain?
+ 0 comments I feel this useDelimiter is also a good fit for this :
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); sc.useDelimiter("[^a-zA-Z]+"); String str = ""; int cnt = 0; while(sc.hasNext()) { cnt++; str = str + "\n" + sc.next(); } System.out.println(cnt + str); sc.close(); } }
Load more conversations
Sort 1608 Discussions, By:
Please Login in order to post a comment