黑马程序员技术交流社区
标题: String类 常用方法 [打印本页]
作者: 果维 时间: 2015-12-24 18:18
标题: String类 常用方法
1、字符串与字符数组之间的转换:
字符串转为字符数组:public char[] toCharArray()
字符数组转为字符串:public String(char[] value)
PublicString(char[] value,int offset,int count)
例:- public class StringAPIDemo01{
- public static void main(String args[]){
- String str1 = "hello" ; // 定义字符串
- char c[] = str1.toCharArray() ; // 将一个字符串变为字符数组
- for(int i=0;i<c.length;i++) // 循环输出
- {System.out.print(c[i] + "、") ; }
- System.out.println("") ; // 换行
- String str2 = new String(c) ; // 将全部的字符数组变为String
- String str3 = new String(c,0,3) ; // 将部分字符数组变为String
- System.out.println(str2) ; // 输出字符串
- System.out.println(str3) ; // 输出字符串
- }
- };
复制代码 2、字符串与字节数组之间的转换:
字符串转字节数组:public byte[] getBytes()
字符数组转字符串:public String(byte[] bytes)
public String(byte[] bytes,int offset,int length)
例:- public class StringAPIDemo02{
- public static void main(String args[]){
- String str1 = "hello" ; // 定义字符串
- byte b[] = str1.getBytes() ; // 将字符串变为byte数组
- System.out.println(new String(b)) ; // 将全部的byte数组变为字符串
- System.out.println(new String(b,1,3)) ; // 将部分的byte数组变为字符串
- }
- };
复制代码 3、字符串与整型数组间的转换:- public class StringAPIDemo03
- {public static void main(String[] args)
- {//字符串转为整型数组:
- String s1="123456789";
- int n1[]=new int[s1.length()];
- for(int i=0;i<n1.length;i++)
- n1[i]=Integer. parseInt(String.valueOf(s1.charAt(i)));
-
- //整型数组转为字符串:
- int n2[]={1,2,3};
- String s2="";
- for(int i=0;i<n2.length;i++)
- s2+=Integer.toString(n2[i]);
- System.out.println(s2);
- }
- }
复制代码 4、获取给定的Index处的字符:
char charAt(int index)
例:public class StringAPIDemo04{
public static void main(String args[]){
String str1 = "java" ; // 定义String对象
System.out.println(str1.charAt(3)) ; // 取出字符串中第四个字符’a’
}
};
作者: 王如是 时间: 2015-12-24 20:33
写的不错
作者: DayBreak 时间: 2015-12-24 21:18
楼上说的好。
作者: anuo 时间: 2015-12-24 21:25
嘿嘿,可以保存,楼主好人,给加精
作者: WaterTheGreat 时间: 2015-12-25 13:16
支持支持!!
作者: 一大把手 时间: 2015-12-25 16:41
很好,总结的可以啊!
作者: 337325635 时间: 2015-12-25 21:15
刚刚学到这 非常有用
作者: luyang18 时间: 2015-12-25 22:16
收藏起来,学到再回看
作者: 鳌少宝 时间: 2015-12-25 22:29
呵呵,不错加油哦
作者: ztg 时间: 2015-12-25 22:38
楼主是哪个校区的
作者: 凤凰城nash 时间: 2015-12-26 00:22
楼主好人
作者: Zrz_K 时间: 2015-12-26 23:09
这个学到了,排版不错
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |