gpt4 book ai didi

Java:我的 split 方法有问题

转载 作者:行者123 更新时间:2023-12-01 12:54:41 25 4
gpt4 key购买 nike

我正在尝试创建一个 split 方法,将从输入文件中读取的行拆分为我返回的字符串数组。问题是,当我通过 for 循环发送诸如“ho;hi hello”之类的行时,它总是在第一个分隔符或 ";" 之后停止。或第一个运算符,例如 "+" 。我不确定为什么要这样做,因为我希望它继续迭代直到行尾,这意味着在 if 语句之后再次迭代 for 循环,直到 i < line.length()

If String line =="ho;hi hello" 

我想要打印出来

This is the string in location 0: ho
This is the string in location 1: ;
This is the string in location 2: hi
This is the string in location 3: hello

目前只是打印出来

This is the string in location 0: ho
This is the string in location 1: ;

始终停在第一个分隔符或运算符处。这是 split 方法的代码。

private static String[] split(String line) {

String temp = ""; //var to store each line from input temporarily
boolean flag = false; //var to check if "\" is in the from input
char[] lineCharArray = line.toCharArray(); //transforms line into array of chars
List<String> array = new ArrayList<String>(); //ArrayList to store the split strings temporarily

for (int i = 0; i<line.length(); i++){
if (!isDelimiter(lineCharArray[i]) && !isOperator(lineCharArray[i]) && flag==false){
//System.out.println(lineCharArray[i]);
temp += lineCharArray[i];
} else {
array.add(temp);
if (isDelimiter(lineCharArray[i])) {
array.add( String.valueOf(lineCharArray[i]));
}
if (isOperator(lineCharArray[i])) {
array.add( String.valueOf(lineCharArray[i]));
}
}
}


String [] strings = new String[array.size()]; //string that is returned for lexical analysis
array.toArray( strings );
for (int i = 0; i<strings.length; i++) {
System.out.println("This is the string in location " + i + ": " + strings[i]);
}
return strings;
}


private static boolean isDelimiter(char c) {
char [] delimiters = {':', ';', '}','{', '[',']','(',')',','};
for (int x=0; x<delimiters.length; x++) {
if (c == delimiters[x]) return true;
}
return false;
}

private static boolean isOperator(char o) {
char [] operators = {'+', '-', '*','/', '%','<','>','=','!','&','|'};
for (int x=0; x<operators.length; x++) {
if (o == operators[x]) return true;
}
return false;
}

最佳答案

我在这里发现了 3 个问题。

  1. 空格不是分隔符,因此预期输出将是:

    This is the string in location 0: ho
    This is the string in location 1: ;
    This is the string in location 2: hi hello
  2. 在向其中添加任何新字符之前,您需要重置 temp。最好使用 StringBufferStringBuilder

  3. 您还需要将最后一个 temp 添加到数组中。

这里我提供修改后的for循环:

for (int i = 0; i<line.length(); i++){
if (!isDelimiter(lineCharArray[i]) && !isOperator(lineCharArray[i]) && flag==false){
//System.out.println(lineCharArray[i]);
temp += lineCharArray[i];
} else {
array.add(temp);
// Resetting temp variable.
temp = "";
if (isDelimiter(lineCharArray[i])) {
array.add( String.valueOf(lineCharArray[i]));
}
if (isOperator(lineCharArray[i])) {
array.add( String.valueOf(lineCharArray[i]));
}
}
}
// Adding last temp to the array.
array.add(temp);

关于Java:我的 split 方法有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23987677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com