-3

To give some context to the title, let's say I have an array of INTs. So, for example (1,2,3,4,5).
Each number in the array represents a char in a string. So if the string is hello then array[3] is going to represent "l".
What is the most efficient or simplest way to remove a char from a string, replace the char and then add it back into the string?
So using the example above I could change "l" to "d", add it back to the string so my final string is "hedlo".

here is part of my code:

method used for max:

 public static int getMax(int[] inputArray){ 
    int maxValue = inputArray[0]; 
    for(int i=1;i < inputArray.length;i++){ 
      if(inputArray[i] > maxValue){ 
         maxValue = inputArray[i]; 
      } 
     } 
    return maxValue; 
    }

here is the code for using the max value in the array as the position in the string results to edit. The char to edit should be replaced with an "m" in the actual case

 int max = getMax(array);
    results.setCharAt(max, 'm');
    String result = results.toString();
Zealot
  • 11
  • 4

2 Answers2

1

Yes, it can easiyl be done. Below I have some code from https://stackoverflow.com/a/4576556/9354346

StringBuilder str = new StringBuilder("hello");
str.setCharAt(2, 'd');
String result = str.toString();
IX33U
  • 85
  • 4
0

Without knowing why you're doing this, I'm not sure exactly what to recommend but here's something to think about. ASCII characters have numerical values associated with them. Table.

If you cast an int to a char, it will convert it to that value. So like,

char c = (char) 97; 

would evaluate to 'a.' If you want 'a' to start at 1, you could just add 96 to everything.

To convert, you could add to an int the difference in the table. So from 'a' to 'd', add 3.

EDIT:

I answered this assuming you were changing an array of ints that was representing a string. Re-reading the question, I'm not sure that's what you're doing! If you need to change a character of a string to a different character, you can use the substring function to grab characters before the change, and after the change and put the new character in the middle.

String x = "Hello";
x = x.substring(0,2) + 'd' + x.substring(3);

This makes x say "Hedlo."

algrice
  • 229
  • 1
  • 4