作为 Codegym 大学课程一部分的导师授课片段。报名参加完整课程。


1 比较字符串

字符串最常见的操作之一是比较。String 类有十多种不同的方法,用于将一个字符串与另一个字符串进行比较。下面我们将看看其中的 8 个主要的。

方法 描述
boolean equals(String str)
如果所有字符都匹配,则认为字符串相等。
boolean equalsIgnoreCase(String str)
比较字符串,忽略字母的大小写(忽略它们是大写还是小写)
int compareTo(String str)
比较字符串,返回从字符串开头开始匹配的字符数。
public int compareToIgnoreCase(String str)
返回字符串开头匹配字符的个数,忽略大小写
boolean regionMatches(int toffset, String str, int offset, int len)
比较部分字符串
boolean startsWith(String prefix)
检查当前字符串是否以该字符串开头prefix
boolean endsWith(String suffix)
检查当前字符串是否以该字符串结尾suffix

假设您要编写一个程序,要求用户提供文件路径,然后根据扩展名检查文件类型。此类程序的代码可能如下所示:

代码 笔记
Scanner console = new Scanner(System.in);
String path = console.nextLine();

if (path.endsWith(".jpg") || path.endsWith(".jpeg"))
{
   System.out.println("This is a jpeg!");
}
else if (path.endsWith(".htm") || path.endsWith(".html"))
{
   System.out.println("This is an HTML page");
}
else if (path.endsWith(".doc") || path.endsWith(".docx"))
{
   System.out.println("This is a Word document");
}
else
{
   System.out.println("Unknown format");
}
创建一个Scanner对象
从控制台读取一行

检查字符串是否path以给定的字符串结尾


2 搜索子串

在比较字符串之后,第二个最流行的操作是在另一个字符串中查找一个字符串。String 类也为此提供了一些方法:

方法 描述
int indexOf(String str)
str在当前字符串中搜索字符串。返回第一次出现的第一个字符的索引。
int indexOf(String str, int index)
str在当前字符串中搜索字符串,跳过第一个index字符。返回出现的索引。
int lastIndexOf(String str)
在当前字符串中搜索字符串str,从末尾开始。返回第一次出现的索引。
int lastIndexOf(String str, int index)
str从末尾搜索当前字符串中的字符串,跳过第一个index字符。
boolean matches(String regex)
检查当前字符串是否与正则表达式指定的模式匹配。

和方法经常结合使用indexOf(String)indexOf(String, index)第一个方法让您找到当前字符串中传递的子字符串的第一次出现。第二种方法允许您通过跳过第一个索引字符来查找第二个、第三个等事件。

假设我们有一个像“ https://domain.com/about/reviews ”这样的 url ,我们想用“ codegym.cc ”替换域名。网址可以有各种不同的域名,但我们知道以下内容:

  • 域名前面有两个正斜杠 - “//”
  • 域名后跟一个正斜杠 - " /"

此类程序的代码如下所示:

代码 笔记
Scanner console = new Scanner(System.in);
String path = console.nextLine();

int index = path.indexOf("//");
int index2 = path.indexOf("/", index + 2);

String first = path.substring(0, index + 2);
String last = path.substring(index2);

String result = first + "codegym.cc" + last;
System.out.println(result);
创建一个 Scanner 对象
从控制台读取一行

获取字符串“ //”第一次出现的
索引 我们获取字符串第一次出现的索引/,但只在字符出现后查找//
我们从字符的开头到结尾获取字符串我们从字符的结尾//
获取字符串。 我们连接字符串和新域。/

和方法lastIndexOf(String)lastIndexOf(String, index)工作方式相同,只是从字符串的末尾到开头执行搜索。



3 创建子串

作为 Codegym 大学课程一部分的导师授课片段。报名参加完整课程。


除了比较字符串和查找子串之外,还有一个非常流行的动作:从字符串中获取子串。碰巧的是,前面的示例向您展示了一个substring()返回部分字符串的方法调用。

以下是从当前字符串返回子字符串的 8 种方法的列表:

方法 描述
String substring(int beginIndex, int endIndex)
返回索引范围指定的子字符串beginIndex..endIndex
String repeat(int count)
重复当前字符串 n 次
String replace(char oldChar, char newChar)
返回一个新字符串:oldChar用字符替换字符newChar
String replaceFirst(String regex, String replacement)
替换当前字符串中由正则表达式指定的第一个子字符串。
public String replaceAll(String regex, String replacement)
替换当前字符串中与正则表达式匹配的所有子字符串。
String toLowerCase()
将字符串转换为小写
String toUpperCase()
将字符串转换为大写
String trim()
删除字符串开头和结尾的所有空格

以下是可用方法的摘要:

substring(int beginIndex, int endIndex)方法

substring方法返回一个新字符串,该字符串由当前字符串中的字符组成,从具有索引的字符开始,beginIndexendIndex. 与 Java 中的所有间隔一样,具有索引的字符endIndex不包含在间隔中。例子:

代码 结果
"Hellos".substring(0, 3);
"Hel"
"Hellos".substring(1, 4);
"ell"
"Hellos".substring(1, 6);
"ellos"
"Hellos".substring(1);
"ellos"

如果endIndex未指定参数(这是可能的),则子字符串将从 beginIndex 处的字符获取到字符串的末尾。

repeat(int n)方法

repeat 方法简单地重复当前字符串的n次数。例子:

代码 结果
"Hello".repeat(3);
"HelloHelloHello"
"Hello".repeat(2);
"HelloHello"
"Hello".repeat(1);
"Hello"
"Hello".repeat(0);
""

replace(char oldChar, char newChar)方法

replace()方法返回一个新字符串,其中所有字符oldChar都替换为字符newChar。这不会改变字符串的长度。例子:

代码 结果
"Programming".replace('Z', 'z');
"Programming"
"Programming".replace('g', 'd');
"Prodrammind"
"Programming".replace('a', 'e');
"Progremming"
"Programming".replace('m', 'w');
"Prograwwing"

replaceFirst()replaceAll()方法

replaceAll()方法将所有出现的一个子字符串替换为另一个子字符串。该replaceFirst()方法用指定的子字符串替换第一次出现的传递的子字符串。要替换的字符串由正则表达式指定。我们将在Java 多线程任务中深入研究正则表达式。

例子:

代码 结果
"Good news everyone!".replaceAll("e.", "EX");
"Good nEXs EXEXyonEX"
"Good news everyone!".replaceAll("o.", "-o-");
"G-o-d news every-o-e!"
"Good news everyone!".replaceFirst("e.", "EX");
"Good nEXs everyone!"
"Good news everyone!".replaceFirst("o.", "-o-");
"G-o-d news everyone!"

toLowerCase() and toUpperCase()方法

当我们第一次学习调用类的方法时,我们就知道了这些方法String

trim()方法

trim()方法从字符串中删除前导和尾随空格。不接触字符串内的空格(即不在开头或结尾)。例子:

代码 结果
"     ".trim();
""
"Hello".trim();
"Hello"
" Hello\n how are you?\n   ".trim();
"Hello\n how are you?\n"
"  Password\n   \n ".trim();
"Password\n   \n"