Remove first word from String

3

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

    
asked by anonymous 28.01.2015 / 22:13

3 answers

5

You can do 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."
    
28.01.2015 / 22:49
6

Use indexOf(String str) and delete(int start, int end)

StringBuffer sb = new StringBuffer("Palavra1 Palavra2");
int index = sb.indexOf(" ");
sb.delete(0, index + 1);//+1 para remover também o espaço
    
28.01.2015 / 22:50
2

To remove a word from a phrase, you 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 of a string , you can use the 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 , you can do:

StringBuffer sb = new StringBuffer("Palavra");
sb.deleteCharAt(sb.length() -1); 
// Ou sb.setLength(sb.length() -1);
System.out.println(sb); // Palavr
    
28.01.2015 / 22:37