string 如何比较 Jsp 中的两个字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31902697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:26:01  来源:igfitidea点击:

How could I compare two string in Jsp?

stringjspsubstring

提问by Sukanta Pal

if(student_code.substring(0,3 )=="MLV")
  count1++;

But count1always return 0

count1总是返回0

回答by Amit.rk3

if(student_code.substring(0,3 )=="MLV")
  count1++;

This doesn't look like a JSP code. It looks more of a scriptlet in JSP, which is nothing but java code. If that's the case, you still need to use equalsfor string comparison, like

这看起来不像 JSP 代码。它看起来更像是 JSP 中的 scriptlet,只不过是 java 代码。如果是这种情况,您仍然需要使用equals字符串比较,例如

if(student_code.substring(0,3 ).equals("MLV"))
      count1++;

If you want to substring and compare strings in JSP, use JSTL functions as shown below

如果要在 JSP 中对字符串进行子串和比较,请使用如下所示的 JSTL 函数

<c:set var="mystring" value="<%=student_code%>"/>

<c:if test="${fn:substring(mystring, 0, 3) == 'MLV'}">
     <%count1++;%>
<c:if>

Also for above JSTL code to work you would need to import below taglibs in JSP

同样要使上述 JSTL 代码工作,您需要在 JSP 中导入以下 taglibs

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

回答by Sukanta Pal

Oho friends .... I just change my code to

哦哦朋友....我只是将我的代码更改为

str1=student_code.substring(0,3 ).trim();
if(str1.equals("YML"))
  count1++;

..and its working

..及其工作

回答by Masutatsu

You can use the '==' symbols to compare two strings in JSP, I would put spaces inbetween and change the double quotes to singles, e.g:

您可以使用 '==' 符号来比较 JSP 中的两个字符串,我会在它们之间放置空格并将双引号更改为单引号,例如:

if(student_code.substring(0,3 ) == 'MLV')

Hopefully this helps.

希望这会有所帮助。

Reference post: How to compare two object variables in EL expression language?

参考帖子:如何比较EL表达式语言中的两个对象变量?