Anurag Anurag - 4 months ago 6x
Java Question

Replacing a searching character in Char array by its index value if it is found

// here i am try to find the location of a char in char array.
if character is resent in the array replace it's original value by its index that is an integer. but when i am try to compile it i got some non- printable out please help me. i mean , when i try access the array element then effect of above operation must be seen.

class Re{

public static void main(String [] args)

Scanner input = new Scanner(;
String enter = input.nextLine();
char [] array = enter.toCharArray();
char find =;
char find2 = Character.toUpperCase(find);
char find3 = Character.toLowerCase(find);
for (int i=0;i<array.length;i++)
if((find2==array[i])|| ( find3==array[i]))
array[i] = (char)(i);
array[i] =array[i];



Unicode has a lot of non-printable characters. See ASCII table for the ones you are probably getting (first 127 characters of UTF-16 are same as ASCII). If you want to convert an integer to its corresponding character value what you can do is add '0' to it.


if (find2 == array[i] || find3 == array[i]) {
    array[i] = (char)(i + '0');

} // omit your else self-assignment, it is redundant

If i > 9 then it is not convertable to a numerical character (only single digit) so you would have to use Strings.


String[] out = new String[array.length];
for (int i = 0; i < array.length; i++) {
    if (array[i] == findUp || array[i] == findLo) {
        out[i] = String.valueOf(i);
    } else {
        out[i] = String.valueOf(array[i]);

You can also use Character#forDigit in the form of Character.forDigit(i, 10) which either returns the above expression ('0' + digit), an alphabetical character if the digit is > 9 ('a' + digit - 10) or a null character if the digit is outside the radix. IE Character.forDigit(10, 10) returns a null character but Character.forDigit(10, 16) (hex) returns 'a'.

When you cast between char and primitive number types (int, short, etc) what you are working with is the Unicode codepoint. For example (char)9 is actually the tab character. Unicode numbers correspond to codes 48-57. Because the numbers are contiguous (0 corresponds to 48, 1 corresponds to 49, 2 corresponds to 50, etc) you can add the value of '0' and get the corresponding character. For example 48 + 2 = 50 so '0' + 2 = '2'. Due to algebra you can also of course convert a character to an integer by subtraction IE '2' - '0' = 2.