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]
5
  • 2
    May we see what code you've tried? Commented May 3, 2016 at 20:18
  • 3
    Don't use new String() for a string literal. You're creating an extra object for nothing. Commented May 3, 2016 at 20:20
  • You could use the replaceFirst() method or use a StringBuilder instead of a String and use the setCharAt() method. Commented May 3, 2016 at 20:24
  • Besides the obsolete new String(…) creation; you don't need to put new ArrayList<String>() in braces. Commented May 3, 2016 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 Commented May 3, 2016 at 20:28

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

modifyingStringMethodhere doesn't exist anywhere

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.