Truncate Sentence

1 minute read

This program was created to trim the sentence and return the first few words in order to simplify the statement/question.

The code has been modified slightly and now uploaded to the site.

<— Return Home

Solution.java

public class Solution {
    public static void main(String[] args) {
        System.out.println(truncateSentence("Hello how are you Contestant", 4));
        System.out.println(truncateSentence("What is the solution to this problem", 4));
        System.out.println(truncateSentence("chopper is not a tanuki", 5));
        // System.out.println(truncateSentence("Hello how are you", 4));
    }
    public static String truncateSentence(String s, int k) {
        String concat = "";
        int beginIndex = 0;
        int counter = 1;
        for (int i = 0; i < s.length(); i++){
            if (s.charAt(i) == ' '){
                counter++;
            }
        }
        String[] array = new String[counter];
        for (int i = 0; i < array.length; i++){
            for (int j = beginIndex; j < s.length(); j++){
                if (s.charAt(j) == ' '){
                    array[i] = s.substring(beginIndex, j);
                    beginIndex = j + 1;
                    break;
                }
                if (j == s.length() - 1){
                    array[i] = s.substring(beginIndex);
                    break;
                }
            }
        }
        // System.out.println(Arrays.toString(array));
        for (int i = 0; i < k; i++){
            if (i == k - 1){
                concat += array[i];
            }
            else {
                concat += array[i] + " ";
            }
        }
        return concat;
    }
}

<— Return Home