-2

I am attempting to remove a substring from the original string

code attempted:

String details = events.event_details.value[bi];
String details2 ="";
if(details.length()>70) {
    details2 = details.substring(70);
    details.replaceFirst(details2, " ");
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
lgrimes12
  • 7
  • 3
  • 1
    Note that a `String` is immutable, `details.replaceFirst(details2, " ")` won't alter `details` at all . – Arnaud Aug 01 '19 at 10:21
  • So you want to take a string, if it's longer than 70 characters, change the first 70 characters to spaces? – Federico klez Culloca Aug 01 '19 at 10:24
  • Hi @lgrimes12 welcome to SO. I recommend to post an actual question in future, as I don't see any question mark. Also please provide some context on what you need to accomplish, e.g. do you need to return the modified string? Do you need to replace with a space or remove? And so on. Please have a look around the site to get a feeling of good questions&answers. – Niccolò Aug 01 '19 at 10:25
  • 2
    @Niccolò good *questions – Federico klez Culloca Aug 01 '19 at 10:29

3 Answers3

0

You do not remove it, you overwrite it with spaces... remove is: cut it off! replace: replace it!

details2 = details.substring(61, 70);

this gives you 10 chars

details2 = details.substring(details.length-10, details.length);

last 10

if you want 60 spaces and then the last 10, you need to create a String with 60 spaces, and use above method to extract whatever you want

maybe use a StringBuffer for this...

StringBuffer strg = new StringBuffer();
String cut = details.substring(details.length-10, details.length);
IntStream.iterate(0, i -> i++).limit(60).forEach((a) -> strg.append(" "));
strg.append(cut);
System.out.println(strg.toString());
Phash
  • 428
  • 2
  • 7
0

You have to save your result from replaceFirst(...) somewhere, as example again in details:

details = details.replaceFirst(details2, "");
tobsob
  • 602
  • 9
  • 22
0

You can try this way-

    String details2 ="";
    String result = ""

    if(details.length()>70) {
        details2 = details.substring(70);
        result = details.replaceFirst(details2, " ");
    }

System.out.println(result);

Here need a String variable where contain that replace's result

Asif
  • 354
  • 3
  • 12