您的位置:首页 > 其它

字符串类常见方法

2015-07-28 17:26 197 查看
package cn.itcast.p1.string.demo;

public class StringDemo {

public static void main(String[] args) {

// TODO Auto-generated method stub

/*

*

* String类特点:

* 字符串对象一旦初始化就不会被改变

*/

stringDemo1();

stringMethodDemo();

}

public static void stringMethodDemo() {

// TODO Auto-generated method stub

/*

* 1 获取

* 1.1按照面向对象的思想对字符串进行分类。

* int length();

*1.2 根据索引获取字符:char charAt(int intdex);

*1.3 根据字符查找字符第一次出现索引:

* int indexOf(int ch) //如果字符不存在返回-1

* int indexOf(int ch, int fromIndex) Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.

* int indexOf(String str)

* int indexOf(String str, int fromIndex)

* 根据字符查找字符最后一次出现索引:

* int lastindexOf(int ch)

* int lastindexOf(int ch, int fromIndex)

* int lastindexOf(String str)

* int lastindexOf(String str, int fromIndex)

* 1.4获取部分字符串

* String substring(int beginIndex, int endIndex) :

* beginIndex - the begin index, inclusive.

* endIndex - the end index, exclusive.

* String substring(int beginIndex)

*

* 2 转换

* 2.1 字符串分割

* !!String[] split(String regex);涉及正则表达式

* 2.2字符串变换为字符数组

* char[] toCharArray()

* 2.3字符串变换为字节数组

* byte[] getBytes()

* 2.4字符串中的字母大小写转换:

* String toLowerCase()

* String toUpperCase()

* 2.5 字符串内容替换

* String replace(char oldChar, char newChar)

* String replace(String target, String replacement)

* 2.6去除字符串两端空格

*!!! String trim()

*2.7字符串连接

*String concat(String str)

*3 判断

*3.1 内容是否相同

*boolean equals(Object anObject)

*boolean equalsIgnoreCase(String anotherString);//忽略大小写

*3.2 字符串是否包含制定字符串

*boolean contains(String str);

*3.3字符串是以指定字符串开头or结尾

*boolean startsWith(String prefix)

*boolean endsWith(String suffix)

*4 比较

*

*!!! int compareTo(String anotherString)

*

*5 String intern()

*/

String s="afd.fe.rer.gtg";

String[] arr=s.split("\\.");

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

System.out.println(arr[i]);

}

s="ab吗";//一个汉子两个字节,汉子转化为二进制高位都为1,所以出现-1

byte[] bytes=s.getBytes() ;

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

System.out.println(bytes[i]);

}

System.out.println("-"+" ab s ".trim()+"-");

}

public static void stringDemo1() {

// TODO Auto-generated method stub,面试题

String s="abc";//常量池创建一个字符串对象

String s1=new String("abc");//堆内存中创建两个对象:一个new/一个字符串对象

System.out.println(s==s1);//false,比较对象

System.out.println(s.equals(s1));//string类重写Object中的equals,所以比较的是字符串内容

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: