Home > other >  Delete the x first words from a string
Delete the x first words from a string

Time:08-10

This function displays only as many dice as you specify in the 'amount'. Now, I want to be able to tell from where it takes the words. From where it starts to display the words. And not always from the beginning.

static String firstTwoWords(String s, int amount, int from) {
    int spaces = 0;
    int i;
    //from = delete the front records from the string
    for (i = 0; i < s.length() && spaces < amount; i  )
        if (s.charAt(i) == ' ') spaces  ;
    return s.substring(0, i);
}

CodePudding user response:

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);
}

I hope i can help

CodePudding user response:

I recommend in this case using this:

String.split(" "); 

The split() methods splits an existing String into substings. The substrings will be stored in a String[].

The split methods works as following:

It takes a "Pattern" (Regex) as a Parameter, that defines where the String has to be split. So if you want to split the String "My name is John", you can use the example above to split the String at all spaces.

The result is the String[], containing the 4 words at the first 4 indexes.

This would look like:

[0] = "My"  
[1] = "name"   
[2] = "is"   
[3] = "John"   

So if you want to delete the first x words from a String, an easy way is to loop from index x to end and to concatenate the remaining indices with a space between them.

  • Related