Printing reverse of any String without using any predefined function?

后端 未结 30 1393
生来不讨喜
生来不讨喜 2020-11-30 03:08

How to print the reverse of the String java is object orientated language without using any predefined function like reverse()?

30条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 03:21

    public static void main(String[] args) {
    
    
        String str = "hello world here I am";
    
        StringTokenizer strToken = new StringTokenizer(str);
        int token = strToken.countTokens();
        String str1 [] = new String[token];
    
        char chr[] = new char[str.length()];
        int counter = 0;
    
        for(int j=0; j < str.length(); j++) {
    
            if(str.charAt(j) != ' ') {
                chr[j] = str.charAt(j);
            }else {
                str1[counter++] = new String(chr).trim();
                chr = new char[str.length()];
            }
        }
        str1[counter++] = new String(chr).trim();
    
        for(int i=str1.length-1; i >= 0 ; i--) {
            System.out.println(str1[i]);
        }
    }
    

    O/P is: am I here world hello

提交回复
热议问题