Some Questions about the split method of string

Source: Internet
Author: User

Today, the first question in leetcode is a simple string reverse output problem. The following is my code:

public String reverseWords(String s) {        if(s == null) return new String("");                StringBuffer fir = new StringBuffer(s);        if(fir.length() == 0) return new String("");                while(fir.length() != 0 && fir.charAt(0) == ‘ ‘){            fir = fir.deleteCharAt(0);        }        if(fir.length() == 0) return new String("");                StringBuffer res = new StringBuffer();        String son[] = fir.toString().split(" ");                for(int i = son.length - 1; i > 0; i--){            //if(son[i].length() == 0) continue;            son[i] = son[i].trim();            res.append(son[i] + " ");        }                    res.append(son[0].trim());        return res.toString();    }

When I use split ("") to cut a string, if consecutive spaces exist, the substring that contains only one space should be cut out, however, the comments in the Code successfully process the substrings that only contain spaces so that they do not appear in the returned results.

That is to say, if the comment row keeps the comment, call: S. reversewords ("this is a blog"), the output will be: "Blog A is this". Note that there are two spaces in the middle of each word, however, if you cancel the comment statement, the result is: "Blog A is this". Here, each word is separated by only one space.

This situation is a bit confusing. I wonder if I can give some insights, so I am afraid that I will forget it. I will put the problem here first...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.