Java字符串的10个入门知识.docx
文本预览下载声明
Java字符串的10个入门知识基本数据类型与字符串之间的转换(1)基本数据类型转字符串? ? 1?基本数据类型+””? ? 2利用String类中的静态方法valueOf(基本数据类型值)? ? 3利用基本数据类型包装类中的方法toString()来获取其字符串表现形式。(2)字符串转基本数据类型? ? ?1在基本数据类型包装类中都有一个静态方法ParseXxx(String str)方法。比如Integer中有parseInt(String str)方法,这个方法返回值为int类型,Double中有parseDouble(String str)此方法返回值为double类型,也就是:Integer.parseXxx(“xxx类型的字符串”)注意点是在Character中没有此方法,因为字符串本就是字符组成的,所以不需要。如果字符串被基本数据类型进行了对象的封装,那么我们可以用非静态的方法xxxvalue()来完成字符串转基本数据类型。例:? ? ? ??Boolean?bl= new Boolean(true);? ? ? ??boolean?x?= bl.booleanValue();对那些安全敏感的信息,为什么用char[]存储要优于String?String是不可变的,这就意味着它一旦被创建,就将永久驻留在内存中,直到垃圾回收器将其回收为止。然而用数组存储方式,你可以明确地改变数组中的元素,因此用数组方式,安全信息将有可能不存在系统内存的任何地方。查找字符串中某个位置的字符 public char charAt(int index);//返回指定索引index位置上的字符,索引范围从0开始如何用空格字符来分割字符串?我们可以很方便地用正则表达式来分割字符串,”s”表示空格字符,比如” “, “t”, “r”, “n”String[] strArray = aString.split(s+);String、StringBuilder和StringBuffer哪个更优?String和StringBuilder:StringBuilder是可变的,也就是说用StringBuilder创建的字符串你可以随时改变它。StringBuilder和StringBuffer:StringBuffer是同步的,它是线程安全(thread-safe)的,但效率要比StringBuilder差得多。 查找指定字符串在字符串中第一次或最后一词出现的位置 在String类中提供了两种查找指定位置的字符串第一次出现的位置的方法 (1)public int indexOf(String str);//从字符串开始检索str,并返回第一次出现的位置,未出现返回-1 (2)public int indexOf(String str,int fromIndex);//从字符串的第fromIndex个字符开始检索str 查找最后一次出现的位置有两种方法 (1)public int lastIndexOf(String str); (2)public int lastIndexOf(String str,int fromIndex); 如果不关心字符串的确切位置则可使用public boolean contains(CharSequence s);如何统计指定字符在字符串中出现的频率同样我们利用了Apache公共语言库中的StringUtils,代码如下:int n = StringUtils.countMatches 1);System.out.println(n);检查字符串的起始字符和结束字符 开始的字符串两种方法 (1)public boolean starWith(String prefix,int toffset);//如果参数prefix表示的字符串序列是该对象从索引toffset处开始的子字符串,则返回true (2)public boolean starWith(String prefix); 结束的字符串方法 public boolean endsWith(String suffix);字符串的替换 两种方法 (1)public String replace(char oldChar,char newChar); (2)public String replace(CharSequence target,CharSequence replacement);//把原来的etarget子序列替换为replacement序列,返回新串 (3)public String replaceAll(String regex,String replacement);//用正则表达式实现对字符串的匹配St
显示全部