0

So we have the following:

ArrayList<String> list = ( new ArrayList<String>( ) );

list.add( new String( "hello" ) ); // add first word at position [0]
list.add( new String( "world" ) ); // add second word at position [1]

I do not want to use the .replace method as that will replace ALL the occurrences. Suppose I only want to modify the first "l" in the hello word and change it to "x", how would I do that? I only want to target a specific element # within the string within the array.

System.out.println( list ); // display the full arraylist

Initial Output:

[hello, world]

Desired Output:

[hexlo, world]
rgettman
  • 176,041
  • 30
  • 275
  • 357
webghost
  • 75
  • 1
  • 5
  • 2
    May we see what code you've tried? – Rabbit Guy May 03 '16 at 20:18
  • 3
    Don't use `new String()` for a string literal. You're creating an extra object for nothing. – shmosel May 03 '16 at 20:20
  • You could use the `replaceFirst()` method or use a `StringBuilder` instead of a `String` and use the `setCharAt()` method. – Bethany Louise May 03 '16 at 20:24
  • Besides the obsolete `new String(…)` creation; you don't need to put `new ArrayList()` in braces. – Holger May 03 '16 at 20:24
  • I think that the question was about working with lists and not only about replacing the characters in strings... it is definetely not an EXACT duplicate of those two answers... You have to consider that you can't change the string "in-place", so you have to manage the addition and removal of the list elements – Igor Deruga May 03 '16 at 20:28

1 Answers1

0

You for example can use the list.set() Method like so:

list.set(index, list.get(index).modifyingStringMethodhere());

Modifying the String, to your desires, is pretty simple, there are tons of tools that java natively supports.

zython
  • 1,176
  • 4
  • 22
  • 50