博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java String compareTo()方法与示例
阅读量:2529 次
发布时间:2019-05-11

本文共 2107 字,大约阅读时间需要 7 分钟。

字符串compareTo()方法 (String compareTo() Method)

compareTo() is a String method in Java and it is used to compare two strings (case-sensitive).

compareTo()是Java中的String方法,用于比较两个字符串(区分大小写)。

If both strings are equal – it returns 0, otherwise, it returns a value less than 0 or greater than 0 based on the first dissimilar characters difference.

如果两个字符串相等–返回0 ,否则,根据第一个不同的字符差返回小于0大于0的值。

Syntax:

句法:

int string1.compareTo(string2);

Here, string1 and string2 are the strings to be compared, and it returns an integer value that is 0, less than 0 or greater than 0.

在这里, string1和string2是要比较的字符串,它返回一个整数值,该值是0,小于0或大于0。

Example:

例:

Input:     str1 = "Hello world!"    str2 = "Hello world!"    Output:    0    Input:     str1 = "Hello world!"    str2 = "HELLO WORLD!"    Output:    32

Java code to compare strings using String.compareTo() method

Java代码使用String.compareTo()方法比较字符串

public class Main{
public static void main(String[] args) {
String str1 = "Hello world!"; String str2 = "Hello world!"; String str3 = "HELLO WORLD!"; System.out.println("str1.compareTo(str2) = " + str1.compareTo(str2)); System.out.println("str1.compareTo(str3) = " + str1.compareTo(str3)); System.out.println("str2.compareTo(str3) = " + str2.compareTo(str3)); //checking with the condition if(str1.compareTo(str2)==0){
System.out.println("str1 is equal to str2"); } else{
System.out.println("str1 is not equal to str2"); } if(str1.compareTo(str3)==0){
System.out.println("str1 is equal to str3"); } else{
System.out.println("str1 is not equal to str3"); } if(str2.compareTo(str3)==0){
System.out.println("str2 is equal to str3"); } else{
System.out.println("str2 is not equal to str3"); } }}

Output

输出量

str1.compareTo(str2) = 0str1.compareTo(str3) = 32str2.compareTo(str3) = 32str1 is equal to str2str1 is not equal to str3str2 is not equal to str3

翻译自:

转载地址:http://motzd.baihongyu.com/

你可能感兴趣的文章
[原创]一篇无关技术的小日记(仅作暂存)
查看>>
20145303刘俊谦 Exp7 网络欺诈技术防范
查看>>
原生和jQuery的ajax用法
查看>>
iOS开发播放文本
查看>>
20145202马超《java》实验5
查看>>
JQuery 事件
查看>>
main(argc,argv[])
查看>>
在线教育工具—白板系统的迭代1——bug监控排查
查看>>
121. Best Time to Buy and Sell Stock
查看>>
hdu 1005 根据递推公式构造矩阵 ( 矩阵快速幂)
查看>>
安装php扩展
查看>>
百度移动搜索主要有如下几类结果构成
查看>>
Python爬虫面试题170道:2019版【1】
查看>>
JavaBean规范
查看>>
第四阶段 15_Linux tomcat安装与配置
查看>>
NAS 创建大文件
查看>>
学习笔记-模块之xml文件处理
查看>>
接口测试用例
查看>>
面试:用 Java 实现一个 Singleton 模式
查看>>
Sybase IQ导出文件的几种方式
查看>>