Home > Blockchain >  element in character array is replaced by '?'
element in character array is replaced by '?'

Time:07-13

I am modifying array like this. But the lower case characters are replaced by '?'. This could be a very basic mistake but I am not able to get it.

String s = new String("ndkcnNKDNKCNnknd");
char[] a = s.toCharArray();
char c;
System.out.println(a[2]);
for (int i=0; i<a.length; i  ){
    if(a[i] >= 'A'){
        a[i] = (char)(a[i]-'A' 'a');
    }
}

s = String.copyValueOf(a);
System.out.println(s);

Output:

k  
?????nkdnkcn????

CodePudding user response:

'a' is bigger 'A'. Note that index/position in Unicode Table of 'a' is 97 (or 0x61 if yo prefer hexadecimal system) while 'A' is 65 (0x41 in hexadecimal).

So if we compare 'a' > 'A' it is same as comparing 97 > 65.

Example:

System.out.println((int)'a'); //97
System.out.println((int)'A'); //65
System.out.println('a'>'A');  //true

This means that our condition if(a[i] >= 'A') also includes all lowercase characters like 'a' 'b'.

To handle only uppercase characters either

  • change >='A' into < 'a'
  • OR add second condition for "maximal" accepted character, like if (a[i]>='A' && a[i]<='Z')
String s = new String("ndkcnNKDNKCNnknd");
char[] a = s.toCharArray();
//char c;
//System.out.println(a[2]);
for (int i = 0; i < a.length; i  ) {
    if (a[i] < 'a') {
        a[i] = (char) (a[i] - 'A'   'a');
    }
}
s = String.copyValueOf(a);
System.out.println(s);

CodePudding user response:

When string is comprised from lower case and upper case English letters condition a[i] >= 'A' is always true. Hence you're altering both lower case and upper case letter in the array.

You can fix the code and make it more expressive by using Character.isUpperCase and Character.toLowerCase.

String source = "ndkcnNKDNKCNnknd";
char[] characters = source.toCharArray();
        
for (int i = 0; i < characters.length; i  ) {
    if (Character.isUpperCase(characters[i])) {
        characters[i] = Character.toLowerCase(characters[i]);
    }
}
    
System.out.println(Arrays.toString(characters));
  • Related