Getting a Character by Index From a String in Java – 在Java中通过索引从一个字符串中获取一个字符

最后修改: 2021年 10月 24日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

The charAt() method of the String class returns the character at a given position of a String. This is a useful method that has been available from version 1.0 of the Java language.

charAt()类的String方法返回String的指定位置的字符。这是一个有用的方法,从Java语言的1.0版本开始就有了。

In this tutorial, we will explore the usage of this method with some examples. We’ll also learn how to get the character at a position as a String.

在本教程中,我们将通过一些例子来探讨这个方法的用法。我们还将学习如何以String.的形式获得某个位置的字符。

2. The charAt() Method

2.charAt()方法

Let’s take a look at the method signature from the String class:

让我们看看String类中的方法签名。

public char charAt(int index) {...}

This method returns the char at the index specified in the input parameter. The index ranges from 0 (the first character) to the total length of the string – 1 (the last character).

该方法返回输入参数中指定索引的字符。索引范围从0(第一个字符)到字符串的总长度-1(最后一个字符)。

Now, let’s see an example:

现在,让我们看一个例子。

String sample = "abcdefg";
Assert.assertEquals('d', sample.charAt(3));

In this case, the result was the fourth character of the string – the character “d”.

在这种情况下,结果是字符串的第四个字符–字符 “d”。

3. Expected Exception

3.预期的例外情况

The runtime exception IndexOutOfBoundsException is thrown if the parameter index is negative or if it’s equal to or greater than the length of the string:

如果参数index为负数或者等于或大于字符串的长度,就会抛出运行时异常IndexOutOfBoundsException

String sample = "abcdefg";
assertThrows(IndexOutOfBoundsException.class, () -> sample.charAt(-1));
assertThrows(IndexOutOfBoundsException.class, () -> sample.charAt(sample.length()));

4. Get Character as a String

4.获取字符作为字符串

As we mentioned earlier, the charAt() method returns a char. Often, we need a String literal instead.

正如我们前面提到的,charAt()方法返回一个char。通常情况下,我们需要一个String字头来代替。

There are different ways to convert the result to a String. Let’s assume below String literal for all the examples:

有不同的方法可以将结果转换为String。让我们在所有的例子中假设下面的String字面。

String sample = "abcdefg";

4.1. Using the Character.toString() Method

4.1.使用Character.toString() 方法

We can wrap the result of charAt() with Character.toString() method:

我们可以用Character.toString()方法来包装charAt()的结果。

assertEquals("a", Character.toString(sample.charAt(0)));

4.2. Using the String.valueOf() Method

4.2.使用String.valueOf() 方法

Finally, we can use the static method String.valueOf():

最后,我们可以使用静态方法String.valueOf()

assertEquals("a", String.valueOf(sample.charAt(0)));

5. Conclusion

5.总结

In this article, we learned how to use the charAt() method to get a character at a given position of a String. We also saw what exceptions could occur when using it and a few different ways of getting the character as a String.

在这篇文章中,我们学习了如何使用charAt()方法来获取String中指定位置的字符。我们还看到了使用它时可能出现的异常,以及将字符作为String的几种不同方式。

And, as always, all the snippets can be found over on Github.

而且,像往常一样,所有的片段都可以在Github上找到over