【问题标题】:Java - How to display all substrings in String without using an arrayJava - 如何在不使用数组的情况下显示字符串中的所有子字符串
【发布时间】:2020-11-15 21:06:19
【问题描述】:

我有一个字符串:

1|name|lastname|email|tel \n
2|name|lastname|email|tel \n

我知道我必须使用循环来显示所有行,但问题是在我的作业中
除了 String 和 System,我不能使用数组或其他类。

我还想不使用排序方法或数组按升序对名称进行排序。

我必须使用 compareTo 方法来比较两个名字吗?

如果是这样,我如何使用 compareTo 方法对名称进行排序。

例如,如果 compareTo 返回 1,则表示该名称大于另一个名称。在那种情况下,我如何管理返回以在字符串中正确排序名称?

【问题讨论】:

  • 如果您不能使用List 或数组,这是否意味着您必须在字符串中就地交换行?例如。如果字符串是C\nB\nA\n,并且您使用bubble sort,您需要在这样排序的同时构建字符串吗? C\nB\nA\nB\nC\nA\nB\nA\nC\nA\nB\nC\n
  • 如果我不能使用数组,我将如何使用冒泡排序来交换名称?

标签: java substring


【解决方案1】:

要像示例中那样显示字符串的所有子字符串,您可以一个一个地遍历所有字符并将它们存储在一个字符串中。每当您点击分隔符(例如 | 或 \n)时,打印最后一个字符串。

这是一个在 Java 中迭代字符串字符的线程: What is the easiest/best/most correct way to iterate through the characters of a string in Java?

如果您还需要在没有数组的情况下按升序对名称进行排序,则需要多次扫描输入 - 对 N 个字符串进行排序至少需要 N*log(N) 步。如果这是一个数据结构问题,PriorityQueue 应该为您解决问题 - 插入所有子字符串,然后以排序方式将它们弹出:)

【讨论】:

  • 遇到分隔符时如何打印最后一个字符串?
【解决方案2】:

在 StoneyKeys 的上一个答案的基础上,由于我无权发表评论,您可以使用一个简单的 if 语句,当 char 是分隔符时,System.out.println() 您之前扫描的字符串。然后您可以将字符串重置为空字符串,以准备扫描下一个字符串。

在 java 中,有特殊的 .equals() 运算符用于字符串和字符,因此当您不会使用 == 来检查字符串或字符时。一定要调查一下。要重置字符串的值,只需为其分配一个新值。这是因为原始变量指向某个字符串,即“YHStan”,通过使其指向“”,我们有效地“重置”了字符串。即scannedstr = "";

请阅读代码并理解每一行代码的作用。示例代码和 cmets 仅供您理解,并非完整的解决方案。

String str ="";
    String value = "YH\nStan";
    
    for (int i=0; i <value.length(); i++) {
        char c = value.charAt(i);
        String strc = Character.toString(c);
        //check if its a delimiter, using a string or char .equals(), if it is print it out and reset the string
        if (strc.equals("\n")) {
            System.out.println(str);
            str ="";
            continue;  // go to next iteration (you can instead use a else if to replace this)
        }
        //if its not delimiter append to str
        str = str +strc;
        //this is to show you how the str is changing as we go through the loop.
        System.out.println(str);
            
    }
    System.out.println(str);     //print out final string result

这给出了以下结果:

是的 永辉 永辉 小号 英石 站 斯坦 斯坦

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-18
    • 2014-09-20
    • 2019-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多