字符串String类学习总结

来源:互联网 发布:灰度共生矩阵实现 编辑:程序博客网 时间:2024/06/13 09:00

一、创建并初始化字符串:

  1、使用字符串常量直接初始化 

String s="hello!";

  2、使用构造方法创建并初始化 String();//初始化一个对象,表示空字符序列

  String(value);//利用已存在的字符串常量创建一个新的对象

   String (char[] value);//利用一个字符数组创建一个字符串

   String(char[] value,int offset,int count);//截取字符数组offset到count的字符创建一个非空串

   String(StringBuffer buffer);//利用StringBuffer对象初始化String对象

二、String类主要方法的使用:

  1、获取长度 *.length();//这与数组中的获取长度不同,*.length;

  2、比较字符串

(1) equals() //判断内容是否相同

   (2)compareTo() //判断字符串的大小关系

   (3)compareToIgnoreCase(String int) //在比较时忽略字母大小写

   (4)==   //(双等号)判断内容与地址是否相同

   (5)equalsIgnoreCase() //忽略大小写的情况下判断内容是否相同

三、查找字符串中某个位置的字符

   public char charAt(int index);//返回指定索引index位置上的字符,索引范围从0开始

四、查找指定字符串在字符串中第一次或最后一词出现的位置

   在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);

   (3)public boolean contains(CharSequence s);//不关心字符串的确切位置,只判断是否包含

  五、检查字符串的起始字符和结束字符

   检查起始字符有两种方法:

   (1)public boolean startsWith(String prefix,int toffset);//如果参数prefix表示的字符串序列是该对象从索引toffset处开始的子字符//串,则返回true

   (2)public boolean startsWith(String prefix);

   检查结束字符的方法:

   public boolean endsWith(String suffix);

  六、截取子串

   (1)public String subString(int beginIndex);//从beginIndex到结束

   (2)public String subString(int beginIndex,int endIndex);//返回的字符串是从beginIndex开始到endIndex-1位置

  七、字符串的替换

   (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);//用正则表达式实现对字符串的匹配

  八、字符串的大小写替转换

   (1)public String toLowerCase(Locale locale);

   (2)public String toLowerCase();

   (3)public String toupperCase(Locale locale);

   (4)public String toUpperCase();

  九、去除字符串首尾空格

   *.trim();//最好自己会用代码实现此功能,考试可能考到

  十、字符串转换

   1、将字符串转换成字符数组

   public char[] toCharArray();

   2、将字符串转换成字符串数组

   public String[] split(String regex);//类似于分割作用

   3、将其它数据类型转化为字符串(常用)

   (1)public static String valueOf(boolean b);

   (2)public static String valueOf(char c);

   (3)public static String valueOf(int i);

   (4)public static String valueOf(long i);

   (5)public static String valueOf(float f);

   (6)public static String valueOf(double d);

   (7)public static String valueOf(char[] data);

   (8)public static String valueOf(Object obj);

0 0
原创粉丝点击