Remove First Word from String

Asked

Viewed 2,210 times

3

I have a stringBuffer with a sentence inside. I need to remove the first word from the string. Making the second word become first and the number of words x-1.

3 answers

6

5


You can do it like this:

StringBuffer str = new StringBuffer("Lorem ipsum dolor sit amet, consectetur adipiscing elit.");
str.replace(0, str.indexOf(" ") + 1, ""); // = "ipsum dolor sit amet, consectetur adipiscing elit."

2

To remove a word from a sentence, one can do:

public static void replaceAll(StringBuffer builder, String from, String to)
   {
      int index = builder.indexOf(from);
      while (index != -1)
      {
         builder.replace(index, index + from.length(), to);
         index += to.length();
         index = builder.indexOf(from, index);
      }

StringBuffer sb = new StringBuffer("Foo Bar Baz Poo");
replaceAll(sb, "Bar", "Laa"); // Vai substituir a palavra "Bar" por "Laa"
System.out.println(sb); // Foo Laa Baz Poo

DEMO


If you want to remove the first character from a string, the method can be used deleteCharAt() that will remove the character at the specified position.

StringBuffer sb = new StringBuffer("Palavra");
sb.deleteCharAt(0);
System.out.println(sb); // alavra

DEMO

To remove the last character from a string, can be made:

StringBuffer sb = new StringBuffer("Palavra");
sb.deleteCharAt(sb.length() -1); 
// Ou sb.setLength(sb.length() -1);
System.out.println(sb); // Palavr
  • but I don’t know the size of the word as it may vary. What would be needed is something like a split, but I don’t think it works with stringBuffer.

  • But I need to take out the whole word and not just the first character.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.