Home java Deleting characters in the

Deleting characters in the

Author

Date

Category

Hello!

There is a string, for example, String Out = "Qwerty"; I want to remove from it from 1 to 3 characters. Is it possible? I read about the Delete method, but it is only for StringBuffer and StringBuilder classes. How is something similar for String? If not, how to properly copy the string from String in StringBuilder or StringBuffer and back?


Answer 1, Authority 100%

As an option, you can use the Substring method (int indexbegin, int indexend), it will return the line from the indexbegin position to the position of indexend. The countdown of characters is kept from scratch. It is also possible to use the same method, with one parameter – indexbegin, which will return to you from the specified index to the end of the line.


Answer 2, Authority 100%

Using String (Yes, he does not have such delete):

If a little text and not too lazy to write something, then it is something like this:

string deletecharacters (String Str, Int From, Int To) {
  Return str.Substring (0, From) + Str.Substring (To);
}

Returns a string with remote characters in the range [Trom, To) (not included with TO)

string out = "qwerty";
Out = Deletecharacters (Out, 1, 3); // QRTY

But I like more when the arguments goes the amount after the first coordinates. Then:

string deleteesomecharacters (String Str, Int From, Int Count) {
  Return Str.Substring (0, From) + Str.Substring (from + Count);
}

And if there is a desire, you can play and write something with cutting more than one range of characters using Varargs (VARARGS), for example:

String DeleteSomecharacters (String Str, Int ... fromCount) {
  STRING NEWSTR = New String (STR);
  int deleter = 0;
  For (int i = 0; i & lt; fromcount.length; i + = 2) {
    NEWSTR = NEWSTR.SUBSTRING (0, FROMCOUNT [I] -Deleter) +
      newstr.substring (fromCount [i] + FromCount [i + 1] -Deleter);
    deleter + = fromCount [i + 1];
  }
  RETURN NEWSTR;
}

Using StringBuffer :

string out = "qwerty";
// Call the designer with a string as an argument
StringBuffer StringBuffer = New StringBuffer (OUT);
stringbuffer.delete (1,3);
Out = stringbuffer.tostring (); // QRTY

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions