Remove white space from string without using trim method?

后端 未结 5 1486
轮回少年
轮回少年 2021-01-27 12:10

given string is \'_home sweet home__\' if user enter the mode as 0 then o/p should be \'home sweet home__\' if user enter the mod

5条回答
  •  甜味超标
    2021-01-27 12:41

    A simple way :

    private static String truncateSpace(String text, int mode)
    {         
        if(mode==0 || mode==2)   
            for (int i = 0; i < text.length(); i++) {                
            if (text.charAt(i) != ' ') {
                text = text.substring(i, text.length());                
                break;
            }
        }
       if(mode==1 || mode==2)
            for (int i = text.length()-1; i > 0; i--) {
                    if (text.charAt(i) != ' ') {
                        text = text.substring(0, i+1);
                        break;
                    }
                }       
        return text;
    }
    

提交回复
热议问题