Question

Java Exercise 19. Given a string, if the first or last chars are 'x', return the...

Java Exercise

19. Given a string, if the first or last chars are 'x', return the string without those 'x' chars, and otherwise return the string unchanged.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
//TrimX.java
public class TrimX {
    public static String trimX(String s){
        String result;
        if(s.charAt(0)=='x' && s.charAt(s.length()-1)=='x'){
            result = s.substring(1,s.length()-1);
        }
        else if(s.charAt(0)=='x'){
            result = s.substring(1);
        }
        else if(s.charAt(s.length()-1)=='x'){
            result = s.substring(0,s.length()-1);
        }
        else{
            result = s;
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(trimX("xabcx"));
        System.out.println(trimX("xabc"));
        System.out.println(trimX("abcx"));
        System.out.println(trimX("abc"));
    }
}

public static String trimX(String s){
    String result;
    if(s.charAt(0)=='x' && s.charAt(s.length()-1)=='x'){
        result = s.substring(1,s.length()-1);
    }
    else if(s.charAt(0)=='x'){
        result = s.substring(1);
    }
    else if(s.charAt(s.length()-1)=='x'){
        result = s.substring(0,s.length()-1);
    }
    else{
        result = s;
    }
    return result;
}

Add a comment
Know the answer?
Add Answer to:
Java Exercise 19. Given a string, if the first or last chars are 'x', return the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT