【问题标题】:Split a string not knowing its length without using split()在不使用 split() 的情况下拆分不知道其长度的字符串
【发布时间】:2021-11-16 14:06:09
【问题描述】:

在用户输入之前我们不知道字符串的长度,但输入格式类似于数字-数字-数字... 这些数字的位数不同。 考虑这个输入 10000-20-150-2-12345-2-1-450000-30-2-50

我只能使用 Scanner(System.in) 并将其保存在字符串中,但不允许使用 parseInt 或 Integer.valueOf 或 toCharArray 或数组或拆分函数将数字提取到数组中。 如何制作拆分功能并使用它? 虽然我考虑过 for 循环和 charAt(i)=='-' 但我不知道如何获取数字。

【问题讨论】:

  • 您尝试过什么了吗?你熟悉 String 的任何方法吗?
  • 提示:Scanner 使用分隔符(默认为空格)来确定如何在其许多读取输入的方法中读取输入。您可以将扫描仪delimiter 设置为您想要的任何内容(包括"-")。
  • 你可以使用Character.isDigit(char c)吗?
  • 连字符(“-”)的数量是否始终相同?

标签: java split


【解决方案1】:

为了将字符串解析为 int,您可以使用:

// Parse string to int without using Integer.parseInt() or Integer.valueOf()
public static int stringToInteger(String str) {
    int answer = 0, factor = 1;
    for (int i = str.length()-1; i >= 0; i--) {
        answer += (str.charAt(i) - '0') * factor;  // '0' is to get the ascii code of 0
        factor *= 10;
    }
    return answer;
}

在您的处理代码中:

  • 你可以用(java 8)知道结果数组的长度:
int[] result = new int[userInput.chars().filter(ch -> ch == '-').count() + 1];
  • 您只需使用charAt(n) 方法遍历userInput 字符串并将char 存储在StringBuilder 中,直到获得“-”,然后调用stringToInteger 方法将int 添加到数组中:
StringBuilder sb = new StringBuilder();
int resultIndex = 0;
char c;
for(int i=0 ; i< userInput.length(); i++) {
    char c = userInput.charAt(i);
    if(c == '-') {
        result[resultIndex++] = stringToInteger(sb.toString());
        sb.setLength(0); // Empty the stringBuilder
    }
    else {
        sb.append(c); // Add char in the stringBuilder
    }
}

【讨论】:

  • 当字符串中的许多数字超过一位时,如何使用 charAt
  • 我不允许使用数组或列表或其他 java 数据结构。我应该自己做一个数据结构吗?
  • 如果 userInput 字符串是“147-....”,则在字符串生成器中添加 '1' (i=0),然后添加 '4' (i=1) 所以 stringbuilder现在等于“14”,然后添加“7”(i=2),因此 stringBuilder 等于 147。当 i=3 时,字符为“-”,因此您解析 stringBuilder(即“147”)进入 int 并将 147 保存在数组中。等等......所以你必须在不使用数组的情况下存储一个 int 数组?这很奇怪?所以将“147-23-.....”存储在一个字符串(userInput)中并自定义您的方法,以便它采用参数索引,例如返回147的getInt(0),返回147的getInt(1) 23...通过解析字符串
  • 例如,您可以创建一个具有 String 属性的类MyData,以及一个可以处理字符串的方法getInt(int index),以便您可以调用:MyData data = new MyData("156-28-26-381") ; data.getInt(0) // return 156 ; data.getInt(2) // return 26 ; data.getInt(4) // throw an arror
【解决方案2】:

这是一个没有什么花哨的例子,只是String.charAt()

String input = "10000-20-150-2-12345-2-1-450000-30-2-50";
String curValue = "";
for(int i=0; i<input.length(); i++) {
  char c = input.charAt(i);
  if (!(c == '-')) {
    curValue = curValue + c;
  }
  else {
    // ... do something with curValue ...
    System.out.println(curValue);

    // reset curValue
    curValue = "";
  }
}
if (curValue.length() > 0) {
  // ... do something with curValue ...
  System.out.println(curValue);
}

我们只是迭代字符并将它们累积在“curValue”中,直到您击中破折号。然后处理“curValue”中的内容并将其重置为空白字符串。迭代所有字符后,您需要处理“curValue”中剩余的最后一个值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-12
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多