一、常規字符串匹配
在Java中,我們可以使用equals()方法來比較兩個字符串是否相等,如下示例代碼:
String str1 = "hello"; String str2 = "world"; if(str1.equals(str2)){ System.out.println("str1和str2相等"); }else{ System.out.println("str1和str2不相等"); }
以上代碼中,我們使用equals()方法比較了str1和str2兩個字符串是否相等。
還可以使用compareTo()方法來比較兩個字符串,如下示例代碼:
String str1 = "hello"; String str2 = "world"; int result = str1.compareTo(str2); if(result == 0){ System.out.println("str1和str2相等"); }else if(result < 0){ System.out.println("str1小於str2"); }else{ System.out.println("str1大於str2"); }
以上代碼中,我們使用compareTo()方法比較了str1和str2兩個字符串的大小關係。
二、正則表達式匹配
在Java中,我們可以使用正則表達式來匹配字符串,如下示例代碼:
String str = "hello world"; if(str.matches("hello.*")){ System.out.println("str匹配成功"); }else{ System.out.println("str匹配失敗"); }
以上代碼中,我們使用matches()方法和正則表達式”hello.*”來匹配字符串str。
還可以使用Pattern和Matcher類來進行正則表達式匹配,如下示例代碼:
String str = "hello world"; Pattern pattern = Pattern.compile("hello.*"); Matcher matcher = pattern.matcher(str); if(matcher.matches()){ System.out.println("str匹配成功"); }else{ System.out.println("str匹配失敗"); }
以上代碼中,我們使用Pattern和Matcher類來匹配字符串str和正則表達式”hello.*”。
三、字符串查找替換
在Java中,我們可以使用indexOf()方法來查找字符串中的子串位置,如下示例代碼:
String str = "hello world"; int index = str.indexOf("world"); if(index != -1){ System.out.println("子串'world'在str中的位置是" + index); }else{ System.out.println("str中沒有子串'world'"); }
以上代碼中,我們使用indexOf()方法來查找字符串str中的子串”world”的位置。
還可以使用replace()方法來替換字符串中的子串,如下示例代碼:
String str = "hello world"; String newStr = str.replace("world", "Java"); System.out.println("替換前的字符串是:" + str); System.out.println("替換後的字符串是:" + newStr);
以上代碼中,我們使用replace()方法來將字符串str中的子串”world”替換為”Java”。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/240611.html