简体   繁体   中英

String converting to Char and then to Int

I'm writing a palindrome function for school which will take a string argument and remove all punctuation. For the purpose of my class, I have to use the substring() method.

My code basically takes a substring of each character in the string argument and converts it to char, and then to int. Then, it checks if that integer is within the ASCII numbers for az or AZ and if it is, that substring is appended to a blank string (s2).

My main issue now is that when I try to compile the program, I get an error saying that the substring can't be converted to char. Any ideas on why?

  public Palindrome(String s)
    {
        for(int i = 0; i < s.length(); i++)
        {
//                                      checks if the character is an uppercase letter
            if((int) Character.valueOf(s.substring(i, i + 1)) >= 65)
                if((int) Character.valueOf(s.substring(i, i + 1)) <= 90)
                    s2 += s.substring(i, i+1);
//                                      checks if the character is a lowercase letter
            if((int) Character.valueOf(s.substring(i, i + 1)) >= 97)
                if((int) Character.valueOf(s.substring(i, i + 1)) <= 122)
                    s2 += s.substring(i, i+1);
        }
    }

Character#valueOf(char c) method applies on character and As JavaDoc Says substring ()

public String substring() 

method returns String , So you can not use Character#valueOf method in here

A String object is not a Character or char , even if the length of the String is one. Casting is just trying to fool the compiler, it does not change the actual underlying object.

If String#charAt() is forbidden, then you can use String#toCharArray() that will return a char[] (of length 1 in your case). eg

char[] myChar = s.substring(i, i + 1);
// myChar[0] contains the character

Then to test if it's a letter, you can use

Character.isLetter(myChar[0]);

Beware that when you cast

(int)Character.valueOf(...)

A Character object as returned by valueOf() , is not a char . It will actually work, because the compiler will do some unboxing of Character to char .

If you want to use the ASCII code instead of Character#isLetter() , you can do:

char[] myChar = s.substring(i, i + 1);
int theCharAsInt = (int)myChar[0];
// proceed to test the range 

Because a native char value can be read as a native int value.

int codeA = (int)'A';  // codeA == 65

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM