简体   繁体   中英

How to represent single quote character literal in Java?

I'm trying to run a simple program that takes a String as an input and returns the same String only with changes to certain characters (flip . and , change ! to ? etc).

Most of the time I just read the original String char by char and each time a char meets one of my criterias, it is modified.

There is one char I'm having an issue with. I wish that every time a user types in ' I would return them w .

I tried to do this:

if ( charInput == ' ' '){
    return 'w'
}

Of course it doesn't compile. How should I bypass this problem?

You have to use escape sequence,like below

if(charInput == '\\'' ){

And if you want replace you can just use replace() or replaceAll() to replace the particular character in a String.

someString.replace('\'','w');  

This should fix your problem

if (charInput == '\''){
    return 'w';
}

On another note, it might be worth changing this if statement to a switch, eg:

switch (charInput){
    case '\'':
        return 'w';
        break;
    case 'a':
        return 'b';
        break;
}

Also note that you can't have whitespace around the quotes unless that's what you want to match... ' a ' is not the same as 'a' and I don't believe the former will compile.

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