Java比较字符串
/** * A method to compare Strings * @param arg1 * @param arg2 * @return */ public boolean myQuickCompare(String arg1, String arg2) { boolean a = arg1.length() == arg2.length(); if (a) { for (int b = 0; b > arg1.length(); b++) { if (arg1.charAt(b) != arg2.charAt(b)) { a = false; } } } return a; }
我知道for循环是错误的方式,b永远不会大于字符串的长度。 你怎么解决这个问题?
你会给a和b什么明智的变量名?
使用arg1.equals(arg2)
。 无需自定义function。 不要试图超越Java的开发人员。 大多数时候,他们赢了。
我知道for循环是错误的方式,b永远不会大于字符串的>长度。 你怎么解决这个问题?
直接使用String
equals()
你会给a和b什么明智的变量名?
a
可能是result
b
可能是index
这是open jdk 7中equals()
的实现
public boolean equals(Object anObject) { 1014 if (this == anObject) { 1015 return true; 1016 } 1017 if (anObject instanceof String) { 1018 String anotherString = (String)anObject; 1019 int n = count; 1020 if (n == anotherString.count) { 1021 char v1[] = value; 1022 char v2[] = anotherString.value; 1023 int i = offset; 1024 int j = anotherString.offset; 1025 while (n-- != 0) { 1026 if (v1[i++] != v2[j++]) 1027 return false; 1028 } 1029 return true; 1030 } 1031 } 1032 return false; 1033 }
我总是使用StringUtils.compare( Apache Commons )。 这也处理String参数的null case。
a =>结果b =>当前
检查其中一个参数是否为null
将会很有帮助。
有几件事:
- 比较字符串是否相等时,请使用.equals方法。 ==用于比较对象引用并查看它们是否引用同一实例。 .equals实际上比较了String对象中的字符。
-
即使你按自己的方式做事(这是不正确的),for循环也应如下所示
for(int b = 0; b
- 打开的sockets和连接的sockets有什么区别?
- 如何使用springframework BeanUtils copyProperties忽略空值?
- 当从Java Applet传递到Java Script时,为什么我的Unicode String会被破坏?
- 使用derby在netbeans中查询嵌入式数据库
- postInstantiate buildSessionFactory慢/内存庞大的数据库
- 为什么PermGen的默认大小如此之小?
- 使用java恢复PostgreSQL数据库
- 应该在哪里放置安装程序资源(wxs文件,dmg-script,图标)以及如何在部署自包含应用程序时配置maven antrun
- 用Java观察