Java中的字符串(一)

您所在的位置:网站首页 idea去除空格 Java中的字符串(一)

Java中的字符串(一)

2024-07-03 12:56| 来源: 网络整理| 查看: 265

在亲爱的老王的建议下觉得写博客来记录学习生活确实是个不错的idea。

其实在此之前两度想要写博客,一次是刚刚决定做CTF的时候,一次是用ege做完三级项目之后,但是都因为时间问题耽搁了~~

今天先开一个头,关于ege图形库部分会在事后补上,这次绝对不坑。

转入正题,简单的记录一下Java中的字符串的相关操作——去除字符串中首尾的空格。

 

例如:已知字符串“  string  ”,该字符串首尾各有两个空格,现需要实现的功能是去除首尾的空格,即输出“string”

 

方法一:利用java中已有的方法

在java.lang.String中已定义了去除字符串首尾空格字符的方法:String trim()

代码如下:

public class String_D { public static void main(String[] args) { String str = " string "; str = str.trim(); System.out.println(str); } }

         输出结果为:string

 

 

方法二:自己编写算法实现

 如果不想利用已有的方法,也可以自己写一段小算法来实现该功能。

首先我们要了解java中的string类型在底层可以看作一个字符数组,其拥有length属性,我们也可以通过其索引(下角标)来定位到字符串的单个字符上,在此我们介绍两个相关的方法。

①char charAt(index) 返回指定位置上的字符

例如如下代码:

public class String_D { public static void main(String[] args) { String str = "abcdef"; System.out.println(str.charAt(2)); } }

其输出结果为:c

在此需要注意的是,因为底层为字符数组,所以索引是从0开始的。 

 

 ②String substring (int beginIndex)/String substring (int beginIndex,int endIndex) 返回从beginIndex开始的子字符串(字串)/返回从beginIndex开始到endIndex结束的子字符串(字串)

需要注意的是此字符串是左闭右开的,即输出beginIndex位而不输出endIndex位。

通过如下代码展示其基本用法:

public class String_D { public static void main(String[] args) { String str = "abcdef"; System.out.println(str.substring(2)); System.out.println(str.substring(2,4)); } }

其输出结果为:

                 cdef                            cd

 

了解了以上的两个函数后我们就可以设计简单的算法了,想要去掉首尾字符串只要分别确定首尾第一个不是空格的字符的下角标再用substring存入str即可。

代码如下:

public class String_D { public static void main(String[] args) { String str = " string "; int beginIndex = 0;//用于确定第一个不是空格的字符所在的位置 int endIndex = str.length()-1;//用于确定从后起第一个不为0的字符的位置 while(beginIndex < endIndex && str.charAt(beginIndex) == ' ') beginIndex ++; while(beginIndex < endIndex && str.charAt (endIndex) == ' ') endIndex --; str = str.substring(beginIndex, endIndex+1); System.out.println(str); } }

输出结果为:string

 

====================================正经的分割线==========================================

嘤~人家第一次写博客,好紧张

嘤~就这么点东西竟然写了半个多小时

嘤~不知道有没有错,还请大佬们指出啊

嘤嘤嘤~

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3