-1

I'm wanting to replace a character at in a string

jn025
  • 2,755
  • 6
  • 38
  • 73
  • Use String.substring() method. – Hakan Serce Mar 15 '14 at 07:37
  • possible duplicate of [Java - replace a character at a specific index in a string?](http://stackoverflow.com/questions/6952363/java-replace-a-character-at-a-specific-index-in-a-string) – Jason C Mar 15 '14 at 07:40

5 Answers5

1

You could accomplish this by using substring() to pick apart and recreate the string, but another way is to just convert it to a char[] and operate on that, e.g.:

char[] data = captureString[0].toCharArray();
data[strOneRand] = Character.toUpperCase(data[strOneRand]); // or whatever
String outputFinal = new String(data);

An example of accomplishing this with substring() can be found in the accepted answer of Replace a character at a specific index in a string?. An example of doing it with a StringBuilder can be found there as well.

Community
  • 1
  • 1
Jason C
  • 38,729
  • 14
  • 126
  • 182
1

you just need to do this

char[] charArray = captureString[0].toCharArray();
charArray[strOneRand] = THE_NEW_CHARECTOR_YOU_WANT_TO_REPLACE;
String outputFinal = String.copyValueOf(charArray);
Raghvendra Singh
  • 1,775
  • 4
  • 26
  • 53
1

you can also use the utility class StringBuilder like this:

    StringBuilder resultString = new StringBuilder(captureString[0]);
    char replaceMe = captureString[0].charAt(strOneRand);
    resultString.setCharAt(strOneRand, Character.toUpperCase(replaceMe));

    System.out.println(resultString.toString());

The assignment is just for clarification, good luck!

oschlueter
  • 2,596
  • 1
  • 23
  • 46
1
String a = captureString[0].substring(0,strOneRand);
String b = captureString[0].substring(strOneRand,strOneRand+1).toUpperCase;
String c = captureString[0].substring(strOneRand+1);

System.out.println(a+b+c);

replace method will make the first occurrence of chosen character to upper case. if input string is "aaaaa", you will always get "Aaaaa".

Jaemok Lee
  • 167
  • 4
1

Here is what I would do in your situation:

public void replaceChar(String strPassed, int index){

    char strArray[] = strPassed.toCharArray(); 
    strArray[index] = (char)(strArray[index] - 32);
    strPassed[0] = new String(strArray);

}

and then wherever I wanted to convert the character into UpperCase:

replaceChar(capturString[0], strOneRand);
Crystal Meth
  • 589
  • 1
  • 4
  • 16