Customized String Reverse Java

╄→гoц情女王★ 提交于 2020-01-05 04:23:05

问题


I would just like to ask, is there a way to possibly customize the way you reverse strings in java? For example, this is my sample input:

The big blue bird is flying.

is there any way that I can reverse some parts of the string like for example, by 3?

So the output would be:

Theib g beul bi dris ylfing .

The string is reverse every after 3 characters. is this possible?


回答1:


Methodology: Iterate over all the characters of your input string by a parameter (e.g. in your case param=3) Determine the parts to be reversed with the help of a boolean flag. If the partial substring is not to be reversed append it to the result, otherwise append its reverse to the result with the help of a StringBuilder object. Give this code a try, I hope it helps:

public static String customizedReverse(String str, int param)
{
    String result = "";
    boolean reverse = false;
    StringBuilder sb = null;
    int size = str.length(), i = 0;

    if(param > size)
        return str;

    for (i = 0; i < (size/param)*(param); i += param)
    {
        String temp = str.substring(i, i + param);
        if (!reverse)
            result += temp;
        else
        {
            sb = new StringBuilder(temp);
            result += sb.reverse();
        }
        reverse = !reverse;
    }
    // Appending the remaining part of the string       
    if (!reverse)
        result += str.substring(i, size);
    else
    {
        sb = new StringBuilder(str.substring(i, size));
        result += sb.reverse();
    }

    return result;
}


来源:https://stackoverflow.com/questions/9512718/customized-string-reverse-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!