fork(11) download
  1. import java.util.*;
  2. import java.lang.*;
  3.  
  4. class Main {
  5. public static void main (String[] args) throws java.lang.Exception {
  6. String str = "hello, this is a long sentence";
  7. System.out.printf("Replaced: [%s]%n", truncateAfteWords(3, str));
  8. }
  9.  
  10. private static String truncateAfteWords(int n, String str) {
  11. return str.replaceAll("^((?:\\W*\\w+){" + n + "}).*$", "$1");
  12. }
  13. }
Success #stdin #stdout 0.08s 380160KB
stdin
Standard input is empty
stdout
Replaced: [hello, this is]