简体   繁体   中英

How can I leave the punctuation where it is while reversing a string?

I could use some help. I am trying to reverse a String while leaving the punctuation where it is at in the string. I cannot seem to get this to work. For example the string reads "I like to write songs in my spare time." would need to return "time spare my in songs write to like I." Am I missing something here?

public class ReverseString {

public static void main(String[] args) 
{
    String s[] = "I like to write songs in my spare time.".split(" ");
    String answer = "";

    for (int i = s.length - 1; i >= 0; i--) {
        answer += s[i] + " ";
    }

    System.out.println("Reversed String:");
    System.out.println(answer.substring(0, answer.length() - 1));
}

}

You answer.replace(".", "") use this to replace . with ""



public static void main(String[] args) 
        {
            String s[] = "I like to write songs in my spare time.".split(" ");
            String answer = "";

            for (int i = s.length - 1; i >= 0; i--) {
                answer += s[i] + " ";
            }
            answer = answer.replace(".", "");
            System.out.println("Reversed String:");
            System.out.println(answer.substring(0, answer.length() - 1));
        }

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