您的位置:首页 > 编程语言 > Java开发

JAVA学习【知】String类

2008-11-24 23:27 561 查看
String类是JAVA里常用的类

String对象是不可变的,对于学习String类来说最主要的方法就是查API。

API里详细介绍了String类的构造方法和方法。

String的方法有很多 比如

 

char
charAt(int index)

          返回指定索引处的
char
值。
 int
codePointAt(int index)

          返回指定索引处的字符(Unicode 代码点)。
 int
codePointBefore(int index)

          返回指定索引之前的字符(Unicode 代码点)。
 int
codePointCount(int beginIndex, int endIndex)

          返回此
String
的指定文本范围中的 Unicode 代码点数。
 int
compareTo(String anotherString)

          按字典顺序比较两个字符串。
 int
compareToIgnoreCase(String str)

          不考虑大小写,按字典顺序比较两个字符串。
 String
concat(String str)

          将指定字符串联到此字符串的结尾。
 boolean
contains(CharSequence s)

          当且仅当此字符串包含 char 值的指定序列时,才返回 true。
 boolean
contentEquals(CharSequence cs)

          当且仅当此 String 表示与指定序列相同的 char 值时,才返回 true。
 boolean
contentEquals(StringBuffer sb)

          当且仅当此 String 表示与指定的 StringBuffer 相同的字符序列时,才返回 true。
static String
copyValueOf(char[] data)

          返回指定数组中表示该字符序列的字符串。
static String
copyValueOf(char[] data, int offset, int count)

          返回指定数组中表示该字符序列的字符串。
 boolean
endsWith(String suffix)

          测试此字符串是否以指定的后缀结束。
 boolean
equals(Object anObject)

          比较此字符串与指定的对象。
 boolean
equalsIgnoreCase(String anotherString)

          将此
String
与另一个
String
进行比较,不考虑大小写。
static String
format(Locale l, String format, Object... args)

          使用指定的语言环境、格式字符串和参数返回一个格式化字符串。
static String
format(String format, Object... args)

          使用指定的格式字符串和参数返回一个格式化字符串。
 byte[]
getBytes()

 

 

 

等等在这里我们介绍一些常用的方法

 

1.charAt(int index)

 

 

//将字符串“fghjdEQEyteqwDQJWeqwEeqw$%^&*568321”分类 求出 分类后的大写,小写字母以及其他字符的个数;

public class Zimu {

 public static void main(String[] args) {

  String s="fghjdEQEyteqwDQJWeqwEeqw$%^&*568321"; //定义字符串

  int lcount=0,ucount=0,ocount=0;     //小写,大写,其他个数初始为0

  for(int i=0;i<s.length();i++){

   char c = s.charAt(i);      //字符串转换成字符

   if(c>'a'&&c<'z'){

    lcount++;

   }

   else if(c>'A'&&c<'Z'){

    ucount++;

   }

   else 

    ocount++;

  }

  System.out.println(lcount+" "+ucount+" "+ocount);

 }

}

 

 

 

2.split(String regex)

 

 

//将"My,name,is,Split" 以逗号为拆分符号进行拆分 最后的结果为MynameisSplit

public class Split {

    public static void main(String[] args) {

        String s="My,name,is,Split";

        String[] split=s.split(",");    //split方法拆分字符串

        for(int i=0;i<split.length;i++){

            System.out.print(split[i]);

        }

    }

}

 

 

3.valueOf(char c)

 

//计算345678为几位数字

public class ValueOf {

    

    public static void main(String[] args) {

        int i=345678;

        String value =String.valueOf(i);    //将int型转换为字符串型

        System.out.println("i 是"+value.length()+"位数");  //用length求出位数

    }

}

 
如果想弄清楚String类 那么经常去查API弄清楚里面的方法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息