java字符串处理

来源:互联网 发布:linux流量监控命令 编辑:程序博客网 时间:2024/05/29 17:36
substring()它有两种形式,第一种是:String substring(int startIndex)第二种是:String substring(int startIndex,int endIndex)concat() 连接两个字符串replace() 替换它有两种形式,第一种形式用一个字符在调用字符串中所有出现某个字符的地方进行替换,形式如下:String replace(char original,char replacement)例如:String s=”Hello”.replace(’l',’w');第二种形式是用一个字符序列替换另一个字符序列,形式如下:String replace(CharSequence original,CharSequence replacement)trim() 去掉起始和结尾的空格valueOf() 转换为字符串toLowerCase() 转换为小写toUpperCase() 转换为大写length() 取得字符串的长度例:char chars[]={’a',’b’.’c'};String s=new String(chars);int len=s.length();charAt() 截取一个字符例:char ch;ch=”abc”.charAt(1); 返回值为’b’getChars() 截取多个字符void getChars(int sourceStart,int sourceEnd,char target[],int targetStart)sourceStart 指定了子串开始字符的下标sourceEnd 指定了子串结束后的下一个字符的下标。因此,子串包含从sourceStart到sourceEnd-1的字符。target 指定接收字符的数组targetStart target中开始复制子串的下标值例:String s=”this is a demo of the getChars method.”;char buf[]=new char[20];s.getChars(10,14,buf,0);getBytes()替代getChars()的一种方法是将字符存储在字节数组中,该方法即getBytes()例:String s = “Hello!你好!”; byte[] bytes = s.getBytes(); toCharArray()例:String s = “Hello!你好!”; char[] ss = s.toCharArray();equals()和equalsIgnoreCase() 比较两个字符串regionMatches() 用于比较一个字符串中特定区域与另一特定区域,它有一个重载的形式允许在比较中忽略大小写。boolean regionMatches(int startIndex,String str2,intstr2StartIndex,int numChars)boolean regionMatches(boolean ignoreCase,int startIndex,Stringstr2,int str2StartIndex,int numChars)startsWith()和endsWith()startsWith()方法决定是否以特定字符串开始,endWith()方法决定是否以特定字符串结束equals()和==equals()方法比较字符串对象中的字符,==运算符比较两个对象是否引用同一实例。例:String s1=”Hello”;String s2=new String(s1);s1.eauals(s2); //trues1==s2;//falsecompareTo()和compareToIgnoreCase() 比较字符串indexOf()和lastIndexOf()indexOf() 查找字符或者子串第一次出现的地方。lastIndexOf() 查找字符或者子串是后一次出现的地方。StringBuffer构造函数StringBuffer定义了三个构造函数:StringBuffer()StringBuffer(int size)StringBuffer(String str)StringBuffer(CharSequence chars)下面是StringBuffer相关的函数:length()和capacity()一个StringBuffer当前长度可通过length()方法得到,而整个可分配空间通过capacity()方法得到。ensureCapacity() 设置缓冲区的大小void ensureCapacity(int capacity)setLength() 设置缓冲区的长度void setLength(int len)charAt()和setCharAt()char charAt(int where)void setCharAt(int where,char ch)getChars()void getChars(int sourceStart,int sourceEnd,char target[],int targetStart)append() 可把任何类型数据的字符串表示连接到调用的StringBuffer对象的末尾。例:int a=42;StringBuffer sb=new StringBuffer(40);String s=sb.append(”a=”).append(a).append(”!”).toString();insert() 插入字符串StringBuffer insert(int index,String str)StringBuffer insert(int index,char ch)StringBuffer insert(int index,Object obj)index指定将字符串插入到StringBuffer对象中的位置的下标。reverse() 颠倒StringBuffer对象中的字符StringBuffer reverse()delete()和deleteCharAt() 删除字符StringBuffer delete(int startIndex,int endIndex)StringBuffer deleteCharAt(int loc)replace() 替换StringBuffer replace(int startIndex,int endIndex,String str)substring() 截取子串String substring(int startIndex)String substring(int startIndex,int endIndex)
原创粉丝点击