简体   繁体   中英

Convert char array and return as a String

I try to create a method, which get as parameter a String. This String will be splitted and every word will be reversed(without special characters).

I need to make this method returnable and when I tried to realize it, I got just last word of string which I gave as input parameter.

Would you have any ideas, how could I solve this problem?

public String reverse(String inputString) {
    for(String word : inputString.split(" ")){
        char[] letters = word.toCharArray();
        int leftIndex = 0;
        int rightIndex = letters.length - 1;

        while(leftIndex < rightIndex){
            if (!Character.isAlphabetic(letters[leftIndex]))
                leftIndex++;
            else if(!Character.isAlphabetic(letters[rightIndex]))
                rightIndex--;
            else
            {
                char temp = letters[leftIndex];
                letters[leftIndex] = letters[rightIndex];
                letters[rightIndex] = temp;
                leftIndex++;
                rightIndex--;
            }
        }
        inputString = String.valueOf(letters);
    }
    return inputString;
}

I think you are trying to reverse a String. So to reverse a String there is a built in method in Java. You can use the reverse() method of StringBuilder class. For example:-

public String reverse(String input){  

    String words[]=input.split(" ");

    String output="";  

    for(String str:words){  

        StringBuilder sb=new StringBuilder(str);  
        sb.reverse();  
        output += sb.toString()+" ";  
    }  
    return output.trim(); // removes whitespace at the end
}  

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