java中字符串的索引的数据类型_Java字符串字符

字符所在的索引

可以使用charAt()方法从String对象中获取指定索引处的字符。索引值是从零开始的。以下代码在“YIIBAI.COM”字符串中打印索引值和每个索引处对应的字符:

public class Main {

public static void main(String[] args) {

String str = "YIIBAI.COM";

// Get the length of string YIIBAI.COM

int len = str.length();

// Loop through all characters and print their indexes

for (int i = 0; i < len; i++) {

System.out.println(str.charAt(i) + " has index " + i);

}

}

}

上面的代码生成以下结果。

Y has index 0

I has index 1

I has index 2

B has index 3

A has index 4

I has index 5

. has index 6

C has index 7

O has index 8

M has index 9

测试字符串是否为空

测试String对象是否为空,空字符串的长度为零。有三种方法可以检查空字符串:

isEmpty() 方法.

equals() 方法.

获取字符串的长度,并检查它是否为零。

以下代码显示如何使用三种方法:

public class Main {

public static void main(String[] args) {

String str1 = "Hello";

String str2 = "";

// Using the isEmpty() method

boolean empty1 = str1.isEmpty(); // Assigns false to empty1

boolean empty2 = str2.isEmpty(); // Assigns true to empty1

// Using the equals() method

boolean empty3 = "".equals(str1); // Assigns false to empty3

boolean empty4 = "".equals(str2); // Assigns true to empty4

// Comparing length of the string with 0

boolean empty5 = str1.length() == 0; // Assigns false to empty5

boolean empty6 = str2.length() == 0; // Assigns true to empty6

}

}

更改字符的大小写

要将字符串的内容转换为小写和大写,请分别使用toLowerCase()和toUpperCase()方法。

String str1 = new String("Hello"); // str1 contains "Hello"

String str2 = str1.toUpperCase(); // str2 contains "HELLO"

String str3 = str1.toLowerCase(); // str3 contains "hello"

¥ 我要打赏

纠错/补充

收藏

加QQ群啦,易百教程官方技术学习群

注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值