字符串 charat_Java | String.charAt(index)| 从字符串中按索引获取字符

字符串 charat

String.charAt() function is a library function of String class, it is used to get/retrieve the specific character from a string. Where, the index starts from 0 and ends to String.lenght-1.

String.charAt()函数是String类的库函数,用于从字符串中获取/检索特定字符。 其中,索引从0开始,到String.lenght-1结束。

For example, if there is string "Hello", its index will starts from 0 and end to 4.

例如,如果存在字符串“ Hello” ,则其索引将从0开始到4结束。

Note: If you try to access the character out of bounds, an exception StringIndexOutOfBoundsException will generate. So, be careful while using index in the string.

注意:如果您尝试超出范围访问字符,则会生成异常StringIndexOutOfBoundsException 。 因此,在字符串中使用索引时要小心。

Example1:

范例1:

In this example, there is string initialized by "Hello world!" and we have to access its 0th and 7th character.

在此示例中,存在由“ Hello world!”初始化的字符串 并且我们必须访问其 0 7 字符。

public class Example1
{
	public static void main (String[] args) throws java.lang.Exception
	{
		String msg = "Hello world!";

		System.out.println("Character at 0th index: "+ msg.charAt(0));
		System.out.println("Character at 7th index: " + msg.charAt(7));
	}
}

Output

输出量

    Character at 0th index: H
    Character at 7th index: o


Example2:

范例2:

In this example, we have to read a string and print it character by character

在此示例中,我们必须读取字符串并逐个字符打印

import java.util.*;

public class Example2
{
	public static void main (String[] args) throws java.lang.Exception
	{
		//string Object
		String msg = null;
		
		//Scanner class Object
		Scanner scan = new Scanner(System.in);
		
		//input a string
		System.out.println("Input a string: ");
		msg = scan.nextLine();
		
		//printing string character by character
		System.out.println("Input string is: ");
		for(int loop =0; loop<msg.length(); loop++)
			System.out.print(msg.charAt(loop));
	}
}

Output

输出量

    Input a string:  I love programming.
    Input string is: 
    I love programming.


翻译自: https://www.includehelp.com/java/String-charAt-function-to-get-character-by-Index-from-string.aspx

字符串 charat

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值