简体   繁体   English

你如何进行大于或小于字符串的比较

[英]How do you do a compare of more than or less than with string

Hey guys I want to do some comparison with string by string but I don't know-how.嘿伙计们,我想逐个字符串地进行一些比较,但我不知道如何做。

Like if the string of the user input is the same as the array then it will do something or not it will say not an array.就像如果用户输入的字符串与数组相同,那么它会做某事或不做某事,它会说不是数组。

Does anybody have any suggestions to compare string?有人对比较字符串有什么建议吗? but is it possible to compare string?但是可以比较字符串吗? like the code below像下面的代码

Scanner input = new Scanner(System.in);
String Array[] = {"Henry", "Alex"};

System.out.print("Enter a name: ");
String ans = input.nextLine();
 
if (ans > array){
  System.out.println("Name is available");
} else {
  System.out.println("Name is not available"
}

To see if a String is in an Array try要查看字符串是否在数组中,请尝试

    Scanner input = new Scanner(System.in);
    List<String> list = Arrays.asList("Henry", "Alex");

    System.out.print("Enter a name: ");
    String ans = input.nextLine();
     
    if (list.contains(ans)){
      System.out.println("Name is in list");
    } else {
      System.out.println("Name is not in list");
    }

You can iterate the array and compare the string with each element.您可以迭代数组并将字符串与每个元素进行比较。 Once a match is found, you should print the Found message and break the loop.一旦找到匹配项,您应该打印Found消息并中断循环。 If a match is not found throughout the loop, print the Not found message after the loop.如果在整个循环中未找到匹配项,则在循环后打印Not found消息。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String array[] = { "Henry", "Alex" };

        System.out.print("Enter a name: ");
        String ans = input.nextLine();

        boolean found = false;
        for (String s : array) {
            if (s.equals(ans)) {
                System.out.println("Name is available");
                found = true;
                break;
            }
        }

        if (!found) {
            System.out.println("The name does not exist in the array");
        }
    }
}

A sample run:示例运行:

Enter a name: Alex
Name is available

Another sample run:另一个示例运行:

Enter a name: Nisha
The name does not exist in the array

Note that I have used a boolean variable, found to track if ans exists in the array.注意,我使用了boolean变量, found跟踪如果ans阵列中存在。 There is a way to do it even without using such an additional variable:即使不使用这样的附加变量,也有一种方法可以做到:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String array[] = { "Henry", "Alex" };

        System.out.print("Enter a name: ");
        String ans = input.nextLine();
        int i;

        for (i = 0; i < array.length; i++) {
            if (array[i].equals(ans)) {
                System.out.println("Name is available");
                break;
            }
        }

        // If the loop has been completed without `break`, it means `name` does not
        // exist
        if (i == array.length) {
            System.out.println("The name does not exist in the array");
        }
    }
}

A sample run:示例运行:

Enter a name: Alex
Name is available

Another sample run:另一个示例运行:

Enter a name: Nisha
The name does not exist in the array

There is not one way how to detect is value in the list.没有一种方法可以检测列表中的值。 First you have to convert your array into list.首先,您必须将数组转换为列表。 And there is a methods:并且有一个方法:

1. Use 'contains' method 1.使用'包含'方法

List have method called contains() which returns boolean value.列表有一个名为contains()方法,它返回布尔值。 True - if value/object is in the list, false - if value is not in the list. True - 如果值/对象在列表中,false - 如果值不在列表中。
Example:例子:

String[] array = {"apple", "orange"};
List<String> list = Arrays.asList(array);
String value = "apple";

if (list.contains(value)) {
    System.out.println("Value is in the list");
} else {
    System.out.println("Value is not in the list");
}

This is the easiest way how to detect is array contains value/object.这是如何检测数组是否包含值/对象的最简单方法。 Also instead of using .contains() you can use .indexOf() method which returns -1 if value doesn't exist in array.此外,您可以使用.indexOf()方法代替使用.contains() ,如果数组中不存在值,则该方法返回 -1。 It's the oldest way used in other programming languages as well: if (list.indexOf(value) != -1) .它也是其他编程语言中使用的最古老的方法: if (list.indexOf(value) != -1)
The problem with these methods could be when entered value and values in array have a different char cases (upper/lower).这些方法的问题可能是当输入的值和数组中的值具有不同的字符大小写(大写/小写)时。 To solve that you should iterate array and use same char case.要解决该问题,您应该迭代数组并使用相同的字符大小写。


2. Iterating array 2. 迭代数组

Iterating array values can solve problem when string value cases doesn't match. 当字符串值不匹配时,迭代数组值可以解决问题。

Example:例子:

 String[] array = {"Apple", "Orange"}; String value = "apple"; boolean isInArray = false; for (String item : array) { isInArray = item.toLowerCase().equals(value.toLowerCase()); if (isInArray) { System.out.println("Value is in the list"); break; // exiting array iteration when value was found } } if (!isInArray) { // if all array was iterated and no matching value was found System.out.println("Value is not in the list"); }

3. Use collection streams 3.使用集合流

This method works only with Java 8 and later versions. 此方法仅适用于 Java 8 及更高版本。 Then you can use lambda expressions for streams. 然后您可以对流使用 lambda 表达式。 But using streams could be redundant sometimes. 但有时使用流可能是多余的。

Example:例子:

 String[] array = {"apple", "orange"}; List<String> list = Arrays.asList(array); String value = "apple"; boolean isInArray = list.stream().anyMatch(item -> item.toLowerCase().equals(value.toLowerCase())); if (isInArray) { System.out.println("Value is in the list"); } else { System.out.println("Value is not in the list"); }

A bit of info from w3schools :来自 w3schools 的一些信息:

The equals() method compares two strings, and returns true if the strings are equal, and false if not. equals() 方法比较两个字符串,如果字符串相等则返回真,否则返回假。

Tip: Use the compareTo() method to compare two strings lexicographically.提示:使用 compareTo() 方法按字典顺序比较两个字符串。

A sample snippet of code :示例代码片段:

String myStr1 = "Hello";
String myStr2 = "Hello";
System.out.println(myStr1.compareTo(myStr2));

This returns 0 if they are equal.如果它们相等,则返回 0。 If not it returns some value you can run a if else by passing the returned value to a variable if it equals 0 print equal else print not equal如果不是它返回一些值,您可以通过将返回值传递给变量来运行 if else if it equals 0 print equal else print not equal

Hope i have answered希望我已经回答

If you want to search and find if a string is in an array, please check this link for better info https://www.geeksforgeeks.org/check-if-a-value-is-present-in-an-array-in-java/如果您想搜索并查找字符串是否在数组中,请查看此链接以获取更好的信息https://www.geeksforgeeks.org/check-if-a-value-is-present-in-an-array-在 Java/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 您如何比较已转换为整数的字符串的值(大于/小于)? - How do you compare values (greater than/less than) of strings that have been turned into integers? "如何将两个 char 数组相互比较,以查看输入的数组是否比另一个具有多个特定变量?" - How do you compare two char arrays with each other to see if the inputted one has more than one specific variable than the other? 如何检测和删除阵列中两个以上的重复项? - How do you detect and delete more than two duplicates in an Array? 如何在一个循环中分配多个同一字符串? - How do I assign more than one of the same String in a loop? 如何使输出具有多个字符串(Java) - How do make output have more than one string (Java) 如果它少于或多于 4 位,我如何让它显示错误消息? | Java - How do I make it to show an error message if it's less or more than 4 digits? | Java 如果一个或多个变量小于0,如何使if语句不执行并转到else if语句? - How do I make an if statement not execute and go to the else if statement if one or more variables are less than 0? 如何检查数组以查看其偶数是否多于奇数? - How do you check an array to see if it has more even values than odd? 如何使 CSV 文件包含多个用户 - How do you make a CSV file take in more than one user 如何为预期的异常测试方法添加多个案例? - How do you add more than one cases for a expected exception Test methods?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM