字符串除空格倒序输出

Posted lovelingdu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字符串除空格倒序输出相关的知识,希望对你有一定的参考价值。

1、不用正则表达式,split和trim版

String str = "   The   sky    is   blue            ";
        int l=0,r=str.length()-1;
        while(l<r && str.charAt(l)==‘ ‘)
            l++;
        while(r>0&&str.charAt(r)==‘ ‘)
            r--;
        String tempStr=str.substring(l, r+1);//除去两边空格
        System.out.println(tempStr);
        StringBuilder stb=new StringBuilder();
        int lindex=0,rindex=tempStr.length()-1,temp=tempStr.length();
        
        while(rindex>0) 
        {
            while(tempStr.charAt(rindex)!=‘ ‘&& rindex!=0)
            {    
                rindex--;
                //System.out.println(rindex);
            }
            if(rindex==0) {
                stb.append(tempStr.substring(rindex,temp));
                break;
                }
            
            stb.append(tempStr.substring(rindex+1,temp)+" ");
            
            while(tempStr.charAt(rindex)==‘ ‘&& rindex>0)
            {
                rindex--;
                //System.out.println(rindex);
            }
            
            temp=rindex+1;
        }
        System.out.println(stb+"");

2、正则表达式  trim ()  split()版

        String str="   The sky  is    blue      ";
        String[] str2=str.trim().split("\s+");
        for (int i = str2.length-1; i >0; i--) {
            System.out.print(str2[i]+" ");
        }
        System.out.println(str2[0]);

      转义字符  s  空格  +代表多个空格  

      以空格为界,分割字符串

以上是关于字符串除空格倒序输出的主要内容,如果未能解决你的问题,请参考以下文章

带空格字符串的倒序输出

华为OD机试真题 Java 实现单词倒序2022.11 Q4 新题

华为OD机试真题 Python 实现单词倒序2022.11 Q4 新题

华为OD机试真题 C++ 实现单词倒序2022.11 Q4 新题

华为OD机试真题 Java 实现单词倒序2022.11 Q4 新题

华为OD机试真题 Python 实现单词倒序2022.11 Q4 新题