自定义字符串反向的Java [英] Customized String Reverse Java

查看:138
本文介绍了自定义字符串反向的Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想问问,有没有一种方法,可能你定制扭转Java字符串的方式吗?例如,这是我的样本输入:

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:

蓝色大鸟飞。

在那里,我可以扭转例如像字符串的某些部分,由3什么办法?

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

所以输出将是:

Theib摹beul双向DRIS ylfing。

Theib g beul bi dris ylfing .

的字符串是后3个字符每逆转。这可能吗?

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

推荐答案

方法:通过参数迭代的输入字符串的所有字符(例如,你的情况参数= 3)确定的部分用一个布尔标志的帮助下被逆转。如果部分子不被逆转其追加到的结果,其反向否则追加到一个StringBuilder对象的帮助的结果。给这个code一试,我希望它能帮助:

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;
}

这篇关于自定义字符串反向的Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆