Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I get any number of words from a string. And determine the beginning itself. Java

I want to be able to get any number of words back from a string and to be able to determine the beginning myself.

My code

    static String anyWords(String s, int amount, int from) {
    int spaces = 0;
    int i;
   
    for (i = 0; i < sentence.length() && spaces < amount; i++)
        if (sentence.charAt(i) == ' ') spaces++;
    return sentence.substring(0, i);
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this out

static String anyWords(String s, int amount, int from) {
    int spaces = 0;
    int i;
    String[] stringArray = s.split(" ");
    StringBuilder sentence = new StringBuilder();
    for (int j = 0; j < from; j++)
        stringArray[j] = "";
    for (String value : stringArray)
        if (!Objects.equals(value, ""))
            sentence.append(value).append(" ");
    for (i = 0; i < sentence.length() && spaces < amount; i++)
        if (sentence.charAt(i) == ' ') spaces++;
    return sentence.substring(0, i);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading