首页 > 代码库 > Java中String的常用方法
Java中String的常用方法
开发中涉及到大量的对String的处理,熟练掌握String的常用方法,可以提高开发效率。
1. 字符与字符串,常用的方法有:
- public String(char[] value)
- public String(char[] value, int offset, int count)
- public char charAt(int index)
- public char[] toCharArray()
{ //public char charAt(int index) //取出指定索引的字符 String str = "hello"; char c = str.charAt(1); System.out.println(c);}{ //public char[] toCharArray() //字符数组与字符串的转换 String str = "hello"; char[] strInCharArray = str.toCharArray(); for(char item : strInCharArray) { System.out.print(item + " "); } System.out.println();}{ //public char[] toCharArray() //判断一个给定的字符串是否有数字组成 String str = "13212A355565"; char[] strInCharArray = str.toCharArray(); boolean flag = true; for(char item : strInCharArray) { if(item < ‘0‘ || item > ‘9‘) { flag = false; break; } } System.out.print(str + ": "); if(flag) { System.out.println("全部由数字组成!"); } else { System.out.println("不是全由数字组成!"); }}
2. 字节与字符串
- String(byte[] bytes)
- String(byte[] bytes, int offset, int length)
- public byte[] getBytes()
- public byte[] getBytes(Charset charset)
//public byte[] getBytes()//字符串与字节数组的转换String str = "hello world";byte[] strInBytes = str.getBytes();for(byte item : strInBytes){ System.out.println((int)item);}
3. 字符串比较
- public boolean equals(Object anObject)
- public boolean equalsIgnoreCase(String anotherString)
String str1 = "hello";String str2 = "HELLO";System.out.println(str1.equals(str2));//falseSystem.out.println(str1.equalsIgnoreCase(str2));//true
4. 字符串查找
- public boolean contains(CharSequence s)
- public int indexOf(String str)
- public int indexOf(String str, int fromIndex)
- public int lastIndexOf(String str)
- public int lastIndexOf(String str, int fromIndex)
- boolean startsWith(String prefix)
- public boolean startsWith(String prefix, int toffset)
- public boolean endsWith(String suffix)
String str = "hello world";System.out.println(str.indexOf("world"));System.out.println(str.indexOf("l"));System.out.println(str.indexOf("l",5));System.out.println(str.lastIndexOf("l"));
Java中String的常用方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。