java字符串遍历的几种常用方法总结
作者:humor2020 时间:2022-08-19 06:36:41
1、介绍
常见的数据结构和数据类型,如字符串,树,哈希表,栈,队列等,我们经常在做题的时候会遇到遍历他们的情况,所以掌握好这些方法才能在遇到题目的时候打开思路解决问题,掌握好招式才能正式的解决问题,才能有独立完成问题的可能性。
那么我们这篇文章先学习一下字符串的遍历,在力扣热门100题——无重复字符的最大子串一题中,最容易想到的暴力循环方法就需要用到字符串的遍历。
2、具体的遍历方法
2.1 使用 charAt()
length():返回此字符序列的长度。
charAt(int index):返回指定索引处的char值。
那么我们就可以通过for循环遍历字符串从0到length-1的每一个字符。
String str="2022 fight";
for(int i=0;i < str.length();i++) {
System.out.println(str.charAt(i));
}
2.2 使用substring(i ,i+1)
CharSequence subSequence( int beginIndex, int endIndex):返回一个字符序列,该序列是该序列的子序列。
所以就可以通过把beginIndex设定为i,而endIndex设定为i+1,这样每次也是获得一个字符。
String str="2022 fight";
for(int i=0;i < str.length();i++) {
System.out.println(str.substring(i,i+1));
}
2.3 使用toCharArray()
toCharArray():将此字符串转换为字符数组。
这样就可以将字符串先转换成字符数组,然后再用for循环遍历数组即可。
String str="2022 fight";
char[] s = str.toCharArray();
for(int i=0;i < str.length();i++) {
System.out.println(s[i]);
}
2.4 使用getBytes()
getBytes():将String编码为一系列字节序列,然后存储到字节数组中。
当需要遍历字节类型的时候可以用这个方式,这个相对不那么常用。
String str="2022 fight";
byte[] b = str.getBytes();
for(int i=0;i < str.length();i++) {
System.out.println(b[i]);
}
3、总结
因为字符串是非常常用的数据类型,必须掌握,很多操作的对象就是字符串。
通过这几个方法可以看到,其实掌握各种数据类型之间的转换是非常重要的,String类有很多的相关方法。
对于for循环的遍历和数组的遍历也要掌握,在遍历的时候注意数组的上下界。
大家可以只记住其中一种就好,一力破十会,charAt()和toCharArray都是很好理解的方法。
来源:https://blog.csdn.net/humor2020/article/details/123898983
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Mybatis Plus中的流式查询案例
Java中常见死锁与活锁的实例详解
Java基础之关键字final详解
Spring Boot 中application.yml与bootstrap.yml的区别
详解Java注解知识点
![](https://img.aspxhome.com/file/2023/5/60905_0s.png)
springmvc不进入Controller导致404的问题
![](https://img.aspxhome.com/file/2023/2/62102_0s.png)
Spring AOP底层源码详解
Java8新特性之接口中的默认方法和静态方法
![](https://img.aspxhome.com/file/2023/9/68549_0s.jpg)
SpringBoot实现MapperScan添加动态配置(占位符)
es(elasticsearch)整合SpringCloud(SpringBoot)搭建教程详解
![](https://img.aspxhome.com/file/2023/3/69283_0s.jpg)
Mybatis整合达梦数据库的完整步骤记录
![](https://img.aspxhome.com/file/2023/5/59215_0s.png)
使用chatgpt实现微信聊天小程序的代码示例
![](https://img.aspxhome.com/file/2023/0/67500_0s.jpg)
SpringBoot中Jackson日期格式化技巧分享
Spring Bean常用依赖注入方式详解
Java8 stream 中利用 groupingBy 进行多字段分组求和案例
SpringBoot整合WebService服务的实现代码
![](https://img.aspxhome.com/file/2023/2/60542_0s.png)
详解Java的Hibernate框架中的Interceptor和Collection
![](https://img.aspxhome.com/file/2023/2/72572_0s.png)
struts2框架的登录制作图文教程
![](https://img.aspxhome.com/file/2023/1/70981_0s.png)
java过滤器中Filter的ChainFilter过滤链
![](https://img.aspxhome.com/file/2023/5/72575_0s.png)
SpringBoot redis分布式缓存实现过程解析
![](https://img.aspxhome.com/file/2023/1/58541_0s.png)