有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

比较JAVA中字符串内的数值

我有以下两个字符串:

String margin1 = "-1100px";
String margin2 = "-1000px";
String margin3 = "-1300px";

有人能帮我根据字符串中的数值比较make条件吗?例如:

if (/*Numerical value of*/ margin1 /*is between*/ margin2 /*and*/ margin3)
       break;

提前感谢您的帮助


共 (3) 个答案

  1. # 1 楼答案

    我会使用正则表达式来提取模型(-or+)第二个(整数)和最后一个(px) 您可以在java代码上使用这个正则表达式:[+|-]?[0-9]+px$ 你可以在这里测试:https://www.freeformatter.com/java-regex-tester.html#ad-output

    private static final Pattern p = Pattern.compile("^[+|-]?[0-9]+px$");
    
    private int parseCssToken(String token){
    Matcher m = p.matcher(token); // token = "-1200px"
    if (m.find()) {
            // ...then you can use group() methods.
            return Integer.parseInt(m.group(1)); // this will extract 1200
        }
    // throw Exception here if you don't have any match
    }
    :
    :
    // further, you can use your method like this :
    
    if (parseCssToken(margin1) >= parseCssToken(margin2) && 
    parseCssToken(margin1) <= parseCssToken(margin3)){
    // your logic here
    :
    }
    
    
  2. # 2 楼答案

    如前所述,更简单的解决方案可以基于String::replace/replaceAll+Integer.parseInt从包含后缀px的字符串中获取整数值:

    public static int getMarginSimple(String marginPx) {
        return Integer.parseInt(marginPx.replace("px", ""));
    }
    

    另一种方法可能会使用这样一个事实,即^{}可能不会使用给定字符串的整个文本,也就是说,所有后缀都会被悄悄地丢弃

    但是,NumberFormat不是线程安全的,应该为每个线程创建一个单独的实例(例如,使用ThreadLocal):

    private static final ThreadLocal<DecimalFormat> DEFAULT_FORMATTER = ThreadLocal
            .withInitial(() -> new DecimalFormat());
    
    public static int parseMargin(String margin) {
        try {
            return DEFAULT_FORMATTER.get().parse(margin).intValue();
        } catch (ParseException pex) {
            throw new IllegalArgumentException("Failed to parse " + margin, pex);
        }
    }
    

    然而,这将使不同单位的利润率“可比”:

    int in2000 = parseMargin("2000in");
    int mm200  = parseMargin("-200mm");
    int px300  = parseMargin("300px");
    
    System.out.printf("m1=%d, m2=%d, m3=%d%n", in2000, mm200, px300);
    
    m1=2000, m2=-200, m3=300
    

    因此,应对模式进行定制,使'px'后缀成为必需的:

    private static final String PIXEL_FORMAT = "#px;-#px";
    private static final ThreadLocal<DecimalFormat> PIXEL_FORMATTER = ThreadLocal
            .withInitial(() -> new DecimalFormat(PIXEL_FORMAT));
    
    static int parseMarginPx(String marginPx) {
        try {
            return PIXEL_FORMATTER.get().parse(marginPx).intValue();
        } catch (ParseException pex) {
            throw new IllegalArgumentException("Failed to parse margin in pixels: " + marginPx, pex);
        }
    }
    

    然后,按如下方式解析和处理以像素为单位的边距:

    int m1 = parseMarginPx("1000px");
    int m2 = parseMarginPx("-1200px");
    int m3 = parseMarginPx("1300px");
    
    System.out.printf("m1=%d, m2=%d, m3=%d%n", m1, m2, m3);
    
    if (Math.min(m2, m3) <= m1 && m1 <= Math.max(m2, m3)) {
        System.out.printf("Margin m1=%dpx is between m2=%dpx and m3=%dpx%n", m1, m2, m3);
    } else {
        System.out.printf("Margin m1=%dpx is NOT between m2=%dpx and m3=%dpx%n", m1, m2, m3);
    }
    

    输出

    m1=1000, m2=-1200, m3=1300
    Margin m1=1000px is between m2=-1200px and m3=1300px
    
  3. # 3 楼答案

    可以使用整数。parseInt和String。代替 你可以这样做

    if( 
            Integer.parseInt(margin1.replace("px","")) >= Integer.parseInt(margin2.replace("px","")) 
            && Integer.parseInt(margin1.replace("px","")) <= Integer.parseInt(margin3.replace("px",""))
            )
    break;