Java程序访问字符串中的字符


在本文中,我们将使用Java中的charAt()方法访问字符串中的特定字符。该程序将演示如何查找并在字符串中指定位置显示字符。

问题陈述

我们有一个字符串,我们需要检索给定位置的字符。例如,如果我们使用字符串“laptop”,我们希望显示位于第4个位置(基于0的索引)的字符。

输入

"laptop"

输出

String: laptop
Character at 4th position: t

访问字符串字符的步骤

以下是访问字符串字符的步骤:

  • 首先,我们将定义字符串“laptop”。
  • 使用charAt()方法,并将所需位置作为参数(记住索引从0开始)。
  • 打印结果以显示指定位置的字符。

Java程序访问字符串中的字符

以下是一个访问字符串字符的示例:

public class Demo {
   public static void main(String[] args) {
      String str = "laptop";
      System.out.println("String: "+str);
      // finding character at 4th position
      System.out.println("Character at 4th position: "+str.charAt(3));
   }
}

输出

String: laptop
Character at 4th position: t

代码解释

在这个程序中,我们首先用值“laptop”初始化一个字符串str。然后我们调用charAt(3)方法来检索第4个位置(基于0的索引)的字符。charAt()方法返回指定索引处的字符,因此str.charAt(3)返回't',然后将其打印为输出。

更新于:2024年11月11日

33K+ 浏览量

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.