【Java学习】Java中字符串的常见操作
时间:2014-08-29 11:15:08
收藏:0
阅读:245
字符串中包含的字符数,也就是字符串的长度
int length();获取长度
根据位置获取位置上的某个字符
char charAt(int index);
根据字符获取该字符在字符串中位置
int indexOf(int ch) 返回的是ch在字符串中的第一次出现的位置。
int indexOf(int ch,int fromIndex) 从fromIndex指定位置开始,获取ch在字符串中出现的位置。
int indexOf(String str)返回的是str在字符串中的第一次出现的位置。
int indexOf(String str,int fromIndex) 从fromIndex指定位置开始,获取str在字符串中出现的位置。字符串中是否包含某一个子串
boolean contains(str)
字符串是否有内容
boolean isEmpty()
字符串是否以指定内容开头
boolean startsWith(str)
字符串是否以指定内容结尾
boolean endsWith(str)
举例:
public class StringDemo { public static void main(String[] args) { //String s1 = "abidefghijkmln"; //method_1(s1); //method_trans(); //method_replace(); method_split(); } public static void method_split() { String s = "zhansan,lisi,wangwu"; String[] names = s.split(","); for (String name:names) { System.out.println(name); } } public static void method_replace () { String s = "wfjiwfsfhssfgha"; String new_s = s.replace(‘f‘, ‘F‘); sop(s); sop(new_s); } public static void method_trans () { char[] arr = {‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘,‘g‘}; String s = new String(arr,1,3); sop(s); } public static void method_1(String s) { sop(s.length()); sop(s.charAt(5));//当访问的字符串中不存在的角标时会发生StringIndexOutOfBoundsException sop(s.indexOf(‘i‘,6));//如果没有找到就返回-1 } public static void sop (Object obj) { System.out.println(obj); } }
本文出自 “azhome” 博客,请务必保留此出处http://azhome.blog.51cto.com/9306775/1546370
评论(0)