charAt()在Java示例中| Java String charAt()方法

charAt()在Java示例中| Java String charAt()方法是今天的主题。 Java charAt()是一个字符串的方法,它可以帮助我们找到字符串中任何字符的位置。我们必须放置的索引应该在0到(length_of_string – 1)之间。例如,s.charAt(0)将返回实例s表示的字符串的第一个字符。如果在charAt()方法中传递的索引值小于0或大于或等于字符串的长度(索引),则Java String charAt方法将抛出IndexOutOfBoundsException<0|| index>=长度())。

内容概述

  • 1 charAt()在Java示例中
    • 1.1语法:
  • 2 charAt的各种例子()
    • 2.1查找任何给定索引的字符:
    • 2.2 IndexOutOfBoundsException
    • 2.3使用charAt()打印字符串的所有字符
  • 3计算字符的出现次数
  • 4推荐帖子

charAt()在Java示例中

java.lang.String.charAt()方法返回指定索引处的char值。索引的范围从0到length() – 1.序列的第一个char值在索引0处,下一个在索引1处,依此类推,就像数组索引一样。

句法:

character = string_name.charAt(index_position)

因此,charAt()中有一个参数是字符串的索引。

charAt的各种例子()

查找任何给定索引的字符:

在这个方法中,我们将找到字符串中任何字符的位置。

class CharAt { 	public static void main(String args()) { 		String str = "Welcome to AppDividend"; 		// This will return the first char of the string 		char ch1 = str.charAt(0); 		// This will return the 7th char of the string 		char ch2 = str.charAt(6); 		// This will return the 12th char of the string 		char ch3 = str.charAt(11); 		System.out.println("Character at 0 index is: " + ch1); 		System.out.println("Character at 7th index is: " + ch2); 		System.out.println("Character at 12th index is: " + ch3); 	} }

请参阅以下输出。

charAt()在Java中

IndexOutOfBoundsException异常

当我们输入任何字符串的错误索引位置时会发生这种情况。

假设我们有一个长度为5的字符串,所以如果我们写charAt(10)那么那个位置就没有这样的字符。所以我们将得到IndexOutOfBoundExpection。

请参阅以下程序。

class CharAt { 	public static void main(String args()) { 		String str = "Welcome to AppDividend"; 		// here we are giving one index position which is not 		// present actuallu 		char ch = str.charAt(150); 		System.out.println(ch); 	} }

查看输出。

Java String charAt()方法

使用charAt()打印字符串的所有字符

在此示例中,我们使用charAt()打印给定字符串的所有字符。

class CharAt { 	public static void main(String args()) { 		String str = "Welcome to Appdividend"; 		System.out.println("All the characters of the string are: "); 		for (int i = 0; i <= str.length() - 1; i++) { 			System.out.print(str.charAt(i) + " "); 		} 	} }

查看输出。

使用charAt()打印字符串的所有字符

计算字符的出现次数

在这个例子中,我们将使用charAt()方法来计算给定字符串中特定字符的出现次数。这里我们有字符串,我们计算字符串中字符'B'的出现次数。

public class JavaExample { 	public static void main(String() args) { 		String str = "BeginnersBook";  		// initialized the counter to 0 		int counter = 0;  		for (int i = 0; i <= str.length() - 1; i++) { 			if (str.charAt(i) == 'B') { 				// increasing the counter value at each occurrence of 'B' 				counter++; 			} 		} 		System.out.println("Char 'B' occurred " + counter + " times in the string"); 	} }

最后,charAt()在Java例子中| Java String charAt()方法结束了。

推荐帖子

Java中的瞬态关键字

Java内部价格教程

Java教程中的序列化和反序列化

Java文件类教程

Java示例中的StringBuilder类

资讯来源:由0x资讯编译自APPDIVIDEND,版权归作者Ankit Lathiya所有,未经许可,不得转载
你可能还喜欢