- 小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
此文全部内容都是关于java基础阶段----------字符串转换相关内容,附加一些常用字符串方法。
字符串与字符数组之间的转换(常用)
-
字符串 转换为 字符数组:
String a = "asdcaf"; char [] b =a.toCharArray(); //必须为char类型 -
字符数组 转换为 字符串:
char [] a ={"a","b","c"}; String b = new String(a);
延伸:
-
字符串 转 byte[]
String str = "Hello";//声明一个字符串 byte[] srtbyte = str.getBytes();//使用string类的getBytes方法进行转换 -
byte[] 转 string
byte[] srtbyte;//声明一个byte字节数组 String res = new String(srtbyte);
** 字符串与基本类型转换(常用)**
-
整型转换为字符串:
int i =123; String s = Integer.toString (i); -
字符串转换为整型:
第一种:int b = Integer.valueOf(s).intValue(); 注:不加.intValue(),字符串转换成Integer类型,是包装类 第二种:int b = Integer.ParsentInt(s)
字符串与日期转换
-
字符串转日期
1.通过创建SimpleDateFormat对象的实例
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
2.sdf.parse("2021-9-25")
注:这里字符串需要与sdf对象实例定义格式一致
- 日期转字符串
1.通过创建SimpleDateFormat对象的实例
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
2.sdf.format(new Date());
注:这里返回的日期由上面字符串格式定义
附:字符串常用方法
-
str.length() ---获取字符串长度
-
str.concat(str2)----合并字符串
-
str.equals(otherstr)----判别字符串相等
-
str.charAt(i) ---- 获取字符串中的第i个字符
-
str.split(正则表达式)----拆分字符串,结果保存到字符串数组中
-
str.equalsIgnoreCase(otherstr)----判别字符串相等,忽略大小写
-
str.substring(beginIndex,EndIndex)----截取范围内字符串,benginIndex若是0,可不写
-
str.indexOf(char,index)----指定字符在索引位置之后第一次出现该字符的索引号,若index是0可不写
-
str.lastIndexOf(char,index)----指定字符在索引位置之前第一次出现该字符的索引号,若index是0可不写