为了账号安全,请及时绑定邮箱和手机立即绑定

当没有正则表达式的字符发生变化时拆分字符串

当没有正则表达式的字符发生变化时拆分字符串

明月笑刀无情 2021-10-06 10:25:24
有一种方法可以使用正则表达式函数将字符串拆分为重复字符,但我想在不使用它的情况下进行。例如,给定一个字符串,例如:"EE B"我的输出将是一个字符串数组,例如{"EE", " ", "B"}我的方法是:给定一个字符串,我将首先找到字符串中唯一字符的数量,以便我知道数组的大小。然后我会将字符串更改为字符数组。然后我会检查下一个字符是否相同。如果相同,则将它们附加在一起,如果不开始一个新字符串。到目前为止我的代码..String myinput = "EE B";char[] cinput = new char[myinput.length()];cinput = myinput.toCharArray();    //turn string to array of charactersint uniquecha = myinput.length();for (int i = 0; i < cinput.length; i++) {    if (i != myinput.indexOf(cinput[i])) {        uniquecha--;}   //this should give me the number of unique charactersString[] returninput = new String[uniquecha];Arrays.fill(returninput, "");for (int i = 0; i < uniquecha; i++) {    returninput[i] = "" + myinput.charAt(i);    for (int j = 0; j < myinput.length - 1; j++) {        if (myinput.charAt(j) == myinput.charAt(j + 1)) {            returninput[j] += myinput.charAt(j + 1);        } else {            break;        }    }} return returninput;但是第二部分有问题,因为我不知道为什么当字符改变时它没有开始一个新的字符串。
查看完整描述

3 回答

?
慕桂英546537

TA贡献1848条经验 获得超10个赞

您的问题说您不想使用正则表达式,但我认为没有理由要求该要求,除了这可能是家庭作业。如果您愿意在此处使用正则表达式,那么有一个单行解决方案可将您的输入字符串拆分为以下模式:


(?<=\S)(?=\s)|(?<=\s)(?=\S)

这种模式使用环视来分割,无论前面是非空白字符,后面是空白字符,反之亦然。


String input = "EE B";

String[] parts = input.split("(?<=\\S)(?=\\s)|(?<=\\s)(?=\\S)");

System.out.println(Arrays.toString(parts));


[EE,  , B]

    ^^ a single space character in the middle


查看完整回答
反对 回复 2021-10-06
?
守着一只汪

TA贡献1872条经验 获得超3个赞

如果我理解正确,您希望将字符串中的字符分开,以便类似连续的字符保持在一起。如果是这种情况,我会这样做:


public static ArrayList<String> splitString(String str)

{

        ArrayList<String> output = new ArrayList<>();

        String combo = "";


        //iterates through all the characters in the input

        for(char c: str.toCharArray()) {

            //check if the current char is equal to the last added char

            if(combo.length() > 0 && c != combo.charAt(combo.length() - 1)) {

                output.add(combo);    

                combo = "";

            }


            combo += c;

        }

        output.add(combo); //adds the last character


        return output;

}


请注意,我没有使用数组(具有固定大小)来存储输出,而是使用了ArrayList具有可变大小的 。此外,与其检查下一个字符是否与当前字符相等,我更喜欢使用最后一个字符。该变量combo用于在字符转到 之前临时存储它们output。


现在,这是按照您的指南打印结果的一种方法:


public static void main(String[] args) 

{

    String input = "EEEE  BCD DdA";

    ArrayList<String> output = splitString(input);


    System.out.print("[");

    for(int i = 0; i < output.size(); i++) {

        System.out.print("\"" + output.get(i) + "\"");


        if(i != output.size()-1) 

            System.out.print(", ");

    }

    System.out.println("]");

}


运行上述代码时的输出将是:


["EEEE", " ", "B", "C", "D", " ", "D", "d", "A"]


查看完整回答
反对 回复 2021-10-06
  • 3 回答
  • 0 关注
  • 166 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信