JAVA_String类点滴

JAVA_String类点滴

JAVA_String类点滴

关键词String       
                                   

 

1、String构造函数


String 支持几种构造函数,例如:

//默认构造函数
String s = new String();
创建一个String实例,该实例不包含字符。

//被字符数组初始化的字符串
String(char chars[])

char chars[] = {'a','b','c'};
String s = new String(chars);
该构造函数用abc初始化s。

//指定字符数组的一个子区域作为初始化值
String(char chars[],int startIndex,int numChars)

startIndex指定子区域开始的下标,numChars指定所用字符的个数。
char chars[] = {'a','b','c','d','e','f'};
String s = new String(chars,2,3);

//构造一个String对象
string(String strobj)

class Strings
{
 public static void main(String[] args)
 {
  char chars[] = {'a','b','c','d','e','f'};
  String str1 = new String(chars);
  String str2 = new String(str1);
  System out.println(str1);
  System out.println(str2);
 }
}
程序的输出如下:
abcdef
abcdef

//字节数组初始化的构造函数
String(byte asciichars[])
String(byte asciichars[],int startIndex,int numChars)

class bytes
{
 public static void main(String[] args)
 {
  byte ascii[] = {65,66,67,68,69,70};
  String str1 = new String(ascii);
  String str2 = new String(str1,2,3);
  System out.println(str1);
  System out.println(str2);
 }
}
程序的输出如下:
ABCDEF
CDE

 

2、字符串长度


字符串长度是指其所包含的字符个数。调用Length()方法可以得到这个值。

char chars[] = {'a','b','c'};
String s = new String(chars);
System.out.println("Length:" + s.Length());

 

3、字符串连接


通常,JAVA是允许对String 对象进行操作,+运算符是个例外,它可以连接2个字符串。

string age = "90";
String s = "My age is " + age;
System.out.println(s);

字符串输出为My age is 90。
当创建一个很长的字符串时,可以将它拆开,使用+将它们连接起来。

String s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +
           "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" +
    "cccccccccccccccccccccccccccccc";

字符串还可以和其他类型的数据连接。如下:

int age = 90;
String s = "My age is " + age;
System.out.println(s);

程序输出与前面相同。
这是因为在字符串对象中age自动转换为它的字符串形式。然后与前面的字符串连接。
有可能得到意想不到情况,如下程序:

String s = "My age is " + 2 + 4;
System.out.println(s);

程序输出 My age is 24。

这是由于运算符的优先级所造成的。
My age is首先与2的字符串形式连接,然后与4的字符串形式连接。
可以使用()实现2和4的相加。
String s = "My age is " + (2 + 4);

 

4、toString()

 

toString()方法可以确定所创建类的对象的字符串形式。
可以对所创建类toString()方法覆写。可以被用于print()和println()以及连接表达式中。

class Box
{
 double width;
 double height;
 double depth;
 
 Box(double w,double h,double d)
 {
  width=w;
  height=h;
  depth=d;
 }
 
 public String toString()
 {
  return "Dimensions are" + width + "by" + depth + "by" + height + ".";
 }
}
class toStringDemo
{
 public static void main(String[] args)
 {
  Box box1 = new Box(10,20,30);
  String s = "Box:" + box1;
  System.out.println(box1);
  System.out.println(s);
 }
}
当box1对象在连接表达式中使用或出现在println()中时,Box类的toString方法被自动调用。

 

5、截取字符

 

(1)、charAt()
     返回指定索引处的字符,索引范围从0到length()-1。通过charAt()可以获取指定索引的单个字符。

public class test
{
 public static void main(String[] args)
 {
  String s = "abcdefg";
  char d = s.charAt(3);
  System.out.println(d);
 }
}

(2)、getChars()
     从该字符串中拷贝字符到目的字符数组中。
public void getChars(int srcBegin,
                      int srcEnd,
                      char dst[],
                      int dstBegin)

srcBegin - 要复制的字符串中第一个字符的索引。
srcEnd - 要复制的字符串中最后一个字符的索引。
dst - 目标数组。
dstBegin - 目标数组中的开始偏移量。

实例:
public class getChardemo
{
 public static void main(String[] args)
 {
  String s = "change the template for this generated" +
             "file go to Window - Preferences - Java -" +
                "Code Style - Code Templates";
  int i=7;
  int j=20;
  char chars[] = new char[100];
  s.getChars(i,j,chars,50);
  System.out.println(chars);
 }
}
(3)、getBytes()
     从该字符串拷贝字符到目的字节数组中。 每个字节接收对应字符的低8位。
 public void getBytes(int srcBegin,
                      int srcEnd,
                      byte dst[],
                      int dstBegin)

srcBegin - 要复制的字符串中第一个字符的索引。
srcEnd - 要复制的字符串中最后一个字符的索引。
dst - 目标数组。
dstBegin - 目标数组中的开始偏移量。

(4)、toCharArray()
 public char[] toCharArray()

把该字符串转换成一个新的字符数组。

返回:
一个新分配的字符数组,其长度就是该字符串的长度,内容初始化为该字符串表示的字符序列。

public class test
{
 public static void main(String[] args)
 {
  String s = "change the template for this generated";
  char d[]= s.toCharArray();
  for(int i=0;i<d.length;i++)
  System.out.println(d[i]);
 }
}

 

6、字符串比较


(1)、equals()和equalsIgnoreCase()

使用equals()方法比较2个字符串是否相等,区分大小写。
String s1 = "abc";
String s2 = "abc";
System.out.println(s1.equals(s2));

程序输出:True

equalsIgnoreCase()可以忽略大小写。

String s1 = "ABC";
String s2 = "abc";
System.out.println(s1.equalsIgnoreCase(s2));
程序输出:True

(2)、regionMatches(boolean ignoreCase,int toffset,String other,int ooffset,int len);
     regionMatches(int toffset,String other,int ooffset,int len);

上述两个方法用来比较两个字符串中指定区域的子串。入口参数中,用toffset和ooffset分别指出当前字符串中的子串起始位置和要与之比较的字符串中的子串起始地址;len 指出比较长度。前一种方法可区分大写字母和小写字母,如果在 boolean ignoreCase处写 true,表示将不区分大小写,写false则表示将区分大小写。而后一个方法认为大小写字母有区别。由此可见,实际上前一个方法隐含了后一个方法的功能。比如:
String s1= “tsinghua”
String s2=“it is TsingHua”;
s1.regionMatches(0,s2,6,7);
最后一个语句表示将s1字符串从第0个字符“t”开始和s2字符串的第6个字符“T”开始逐个比较,共比较7对字符,由于区分大小写,所以结果为false。
但如果最后一个语句改为:
s1.regionMatches(true,0,s2,6,7);
则结果为true,因为入口参数中true表示忽略大小写区别。


如果 toffset 或 ooffset 是负的,或如果 toffset+length 大于该字符串的长度, 或 ooffset+length 大于参数字符串的长度,那么该方法返回 false 。

(3)、startsWith()和 endsWith()

public boolean startsWith(String prefix,
                           int toffset)
 public boolean startsWith(String prefix)

测试该字符串是否是以指定的前缀开头。
prefix - 前缀。
toffset - 在字符串中查找的起始点。
若参数表示的字符序列是该字符串序列的前缀则返回 true ,否则返回 false 。
若参数表示的字符序列是该对象开始于索引 toffset 处的子字符串前缀则返回 true ,否则返回 false 。

 public boolean endsWith(String suffix)

测试该字符串是否以指定的字符串作后缀。

参数:
suffix - 后缀。
返回:
若参数表示的字符序列是该对象字符序列的后缀则返回 true ,否则返回 false 。

 

7、equals()与==比较


equals()方法比较字符串对象中的字符是否相等
==运算符比较2个对象的引用是否引用相同的实例。

 

8、compareTo()


 public int compareTo(String anotherString)

按词典顺序比较两个字符串。不区分大小写, 比较的基础是字符串中每个字符的 Unicode 值。

参数:
anotherString - 要比较的 String 。
返回:
若参数字符串等于该字符串,则返回 0 ;若该字符串按词典顺序小于参数字符串则返回值小于 0 ;若该字符串按词典顺序大于参数字符串则返回值大于 0 。

compareToIgnoreCase()方法区分大小写。

class testcompare{
 public static void main(String[] args){
String ch[] = {"as","de","gfd","gfd","red"};

for(int i=0;i<ch.length;i++){
   for(int j=i+1;j<ch.length;j++){
 if(ch[j].compareTo(ch[i])<0)
 {
  String t = ch[j];
  ch[j]=ch[i];
  ch[i]=t;
 }
   }
   System.out.println(ch[i]);
}

}
}

 

9、搜索字符串
  
   public int indexOf(int ch)
返回指定字符在此字符串中第一次出现处的索引。如果未出现该字符,则返回 -1。

   public int indexOf(int ch,
                   int startIndex)
从指定的索引开始搜索,返回在此字符串中第一次出现指定字符处的索引。
startIndex 的值没有限制。如果它为负,它和 0 具有同样的效果:将搜索整个字符串。如果它大于此字符串的长度,则它具有等于此字符串长度的相同效果:返回 -1。
如果未出现该字符,则返回 -1。

   public int lastIndexOf(int ch)
返回最后一次出现的指定字符在此字符串中的索引。如果未出现该字符,则返回 -1。

   public int lastIndexOf(int ch,
                       int startIndex)
从指定的索引处开始进行后向搜索,返回最后一次出现的指定字符在此字符串中的索引。
startIndex参数同上。如果在该点之前未出现该字符,则返回 -1。
   public int indexOf(String str)
返回第一次出现的指定子字符串在此字符串中的索引。
如果字符串参数作为一个子字符串在此对象中出现,则返回第一个这样的子字符串的第一个字符的索引;如果它不作为一个子字符串出现,则返回 -1。
   public int indexOf(String str,
                   int startIndex)
从指定的索引处开始,返回第一次出现的指定子字符串在此字符串中的索引。
   public int lastIndexOf(String str)
返回在此字符串中最右边出现的指定子字符串的如果在此对象中字符串参数作为一个子字符串出现一次或多次,则返回最后一个这样的子字符串的第一个字符。如果它不作为一个子字符串出现,则返回 -1。
索引。将最右边的空字符串 "" 视作发生在索引值 this.length() 处。

   public int lastIndexOf(String str,
                       int startIndex)
从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。

 

10、修改字符串

 

(1)substring()
public String substring(int beginIndex)
返回一个新的字符串,它是此字符串的一个子字符串。该子字符串始于指定索引处的字符,一直到此字符串末尾。
 "unhappy".substring(2) returns "happy"
 "Harbison".substring(3) returns "bison"
 "emptiness".substring(9) returns ""

public String substring(int beginIndex,
                        int endIndex)

返回一个新字符串,它是此字符串的一个子字符串。该子字符串从指定的 beginIndex 处开始,一直到索引 endIndex - 1 处的字符。因此,该子字符串的长度为 endIndex-beginIndex。

beginIndex - 开始处的索引(包括)。
endIndex - 结束处的索引(不包括)。

(2)concat()
public String concat(String str)
将指定字符串联到此字符串的结尾。 同“+”运算符功能相同。
 "cares".concat("s") returns "caress"
 "to".concat("get").concat("her") returns "together"

(3)replace()
public String replace(char oldChar,
                      char newChar)
返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 而生成的。

"mesquite in your cellar".replace('e', 'o')
         returns "mosquito in your collar"

(4)
public String trim()
返回字符串的副本,忽略前导空白和尾部空白。

 

11、改变字符串中字符的大小写


  toLowerCase()
  public String toLowerCase()

  转换该 String 为小写。
toUpperCase
 public String toUpperCase()

转换该 String 为大写。

class stringcov
{
 public static void main(String[] args)
 {
  String s1 = "This is A test";
  String s2 = s1.toLowerCase();
  String s3 = s1.toUpperCase();
  System.out.println("lower:" + s2);
  System.out.println("upper:" + s3);
 }
}

 

 原文地址 http://netdomain.bokee.com/4184734.html

 

java String类、StringBuffer类
2008/10/21 08:13 P.M.

介绍一下Java的一些主要类, String类、 StringBuffer类。

Java是一种真正的面向对象的语言,即使是开发简单的程序,也必须设计对象。Java自身也为我们提供了许多已设计好的类,要想灵活使用Java进行编程,熟悉Java的这些主要类将是必不可少的前提条件之一。

String 类 顾名思义,String是串的意思,这个类是字符串常量的类。相信使用过C语言进行编程的人都知道字符串是怎么回事,这里就不再进行赘述了。但有一点要说明的是,Java中的字符串和C语言中的字符串是有区别的。在C语言中,并没有真正意义上的字符串,C语言中的字符串就是字符数组,使用起来非常的灵活。而在Java中,字符串常量是一个类——String类,它和字符数组是不同的。
下面先介绍一下String类的构造函数

public String()

这个构造函数用来创建一个空的字符串常量。
如:String test=new String();
或:
String test;
test=new String();
public String(String value )

这个构造函数用一个已经存在的字符串常量作为参数来创建一个新的字符串常量。
另外值得注意的是,Java会为每个用双引号"......"括起来的字符串常量创建一个String类的对象。如:String k="Hi."; Java会为"Hi." 创建一个String类的对象,然后把这个对象赋值给k。等同于:

String temp=new String("Hi.");
String k=temp;

这个构造函数的用法如:

String test=new String(k); (注:k是一个String类的对象)
String test=new String("Hello, world.");
public String( char value[] )

这个构造函数用一个字符数组作为参数来创建一个新的字符串常量。
用法如:

char z[]={'h','e','l','l','o'};
String test=new String(z);
(注:此时test中的内容为"hello")
public String( char value[], int offset, int count )

这个构造函数是对上一个的扩充,用一句话来说,就是用字符数组value,从第offset个字符起取count个字符来创建一个String类的对象。用法如:

char z[]={'h','e','l','l','o'};
String test=new String(z,1,3);
(注:此时test中的内容为"ell")

注意:数组中,下标0表示第一个元素,1表示第二个元素……
如果 起始点offset 或 截取数量count 越界,将会产生异常

StringIndexOutOfBoundsException
public String( StringBuffer buffer )

这个构造函数用一个StringBuffer类的对象作为参数来创建一个新的字符串常量。
String类是字符串常量,而StringBuffer类是字符串变量,是不同的。StringBuffer类将在后面进行介绍。
String类的方法有:

public char charAt( int index )

这个方法用来获取字符串常量中的一个字符。参数index指定从字符串中返回第几个字符,这个方法返回一个字符型变量。用法如:

String s="hello";
char k=s.charAt(0);
(注:此时k的值为'h')
public int compareTo( String anotherString )

这个方法用来比较字符串常量的大小,参数anotherString为另一个字符串常量。若两个字符串常量一样,返回值为0。若当前字符串常量大,则返回值大于0。若另一个字符串常量大,则返回值小于0。用法如:

String s1="abc";
String s2="abd";
int result=s2.compareTo(s1);
(注:result的值大于0,因为d在ascII码中排在c的后面,则s2>s1)
public String concat( String str )

这个方法将把参数——字符串常量str 接在当前字符串常量的后面,生成一个新的字符串常量,并返回。用法如:
String s1="How do ";
String s2="you do?";
String ss=s1.concat(s2);
(注:ss的值为"How do you do?")
public boolean startsWith( String prefix )

这个方法判断当前字符串常量是不是以参数——prefix字符串常量开头的。是,返回true。否,返回false。 用法如:

String s1="abcdefg";
String s2="bc";
boolean result=s1.startsWith(s2);
(注:result的值为false)
public boolean startsWith( String prefix, int toffset )

这个重载方法新增的参数toffset指定 进行查找的起始点。

public boolean endsWith( String suffix )

这个方法判断当前字符串常量是不是以参数——suffix字符串常量结尾的。是,返回true。否,返回false。用法如:

String s1="abcdefg";
String s2="fg";
boolean result=s1.endsWith(s2);
(注:result的值为true)
public void getChars( int srcBegin, int srcEnd, char dst[], int dstBegin )

这个方法用来从字符串常量中截取一段字符串并转换为字符数组。
参数srcBegin为截取的起始点,srcEnd为截取的结束点,dst为目标字符数组,dstBegin指定将截取的字符串放在字符数组的什么位置。实际上,srcEnd为截取的结束点加1,srcEnd-srcBegin为要截取的字符数,用法如:

String s="abcdefg";
char z[]=new char[10];
s.getChars(2,4,z,0);
(注:z[0]的值为'c',z[1]的值为'd',截取了两个字符 4-2=2)
public int indexOf( int ch )

这个方法的返回值为 字符ch在字符串常量中从左到右第一次出现的位置。若字符串常量中没有该字符,则返回-1。用法如:

String s="abcdefg";
int r1=s.indexOf('c');
int r2=s.indexOf('x');
(注:r1的值为2,r2的值为-1)
public int indexOf( int ch, int fromIndex )
这个方法是对上一个方法的重载,新增的参数fromIndex为查找的起始点。用法如:
String s="abcdaefg";
int r=s.indexOf('a',1);
(注:r的值为4)
public int indexOf( String str )

这个重载方法返回 字符串常量str在当前字符串常量中从左到右第一次出现的位置,若当前字符串常量中不包含字符串常量str,则返回-1。用法如:

String s="abcdefg";
int r1=s.indexOf("cd");
int r2=s.indexOf("ca");
(注:r1的值为2,r2的值为-1)
public int indexOf( String str, int fromIndex )

这个重载方法新增的参数fromIndex为查找的起始点。
以下四个方法与上面的四个方法用法类似,只是在字符串常量中从右向左进行查找。

public int lastIndexOf( int ch )
public int lastIndexOf( int ch, int fromIndex )
public int lastIndexOf( String str )
public int lastIndexOf( String str, int fromIndex )
public int length()

这个方法返回字符串常量的长度,这是最常用的一个方法。用法如:

String s="abc";
int result=s.length();
(注:result的值为3)
public char[] toCharArray()

这个方法将当前字符串常量转换为字符数组,并返回。用法如:

String s="Who are you?";
char z[]=s.toCharArray();
public static String valueOf( boolean b )
public static String valueOf( char c )
public static String valueOf( int i )
public static String valueOf( long l )
public static String valueOf( float f )
public static String valueOf( double d )

以上6个方法可将boolean、char、int、long、float和double 6种类型的变量转换为String类的对象。用法如:

String r1=String.valueOf(true); (注:r1的值为"true")
String r2=String.valueOf('c'); (注:r2的值为"c")
float ff=3.1415926;
String r3=String.valueOf(ff); (注:r3的值为"3.1415926") 

StringBuffer 类

String类是字符串常量,是不可更改的常量。而StringBuffer是字符串变量,它的对象是可以扩充和修改的

String类的构造函数

public StringBuffer()

创建一个空的StringBuffer类的对象。 public StringBuffer( int length )

创建一个长度为 参数length 的StringBuffer类的对象。

注意:如果参数length小于0,将触发NegativeArraySizeException异常。

public StringBuffer( String str )

用一个已存在的字符串常量来创建StringBuffer类的对象。

StringBuffer类的方法有:

public String toString()

转换为String类对象并返回。由于大多数类中关于显示的方法的参数多为String类的对象,所以经常要将StringBuffer类的对象转换为String类的对象,再将它的值显示出来。用法如:

StringBuffer sb=new StringBuffer("How are you?");
Label l1=new Label(sb.toString());

(注:声明一个标签对象l1,l1上的内容为How are you?)

public StringBuffer append( boolean b )
public StringBuffer append( char c )
public StringBuffer append( int i)
public StringBuffer append( long l )
public StringBuffer append( float f )
public StringBuffer append( double d )

以上6个方法可将boolean、char、int、long、float和double 6种类型的变量追加到StringBuffer类的对象的后面。用法如:

double d=123.4567;
StringBuffer sb=new StringBuffer();
sb.append(true);
sb.append('c').append(d).append(99);
(注:sb的值为truec123.456799)
public StringBuffer append( String str )

将字符串常量str追加到StringBuffer类的对象的后面。

public StringBuffer append( char str[] )

将字符数组str追加到StringBuffer类的对象的后面。

public StringBuffer append( char str[], int offset, int len )

将字符数组str,从第offset个开始取len个字符,追加到StringBuffer类的对象的后面。  

public StringBuffer insert( int offset, boolean b )
public StringBuffer insert( int offset, char c )
public StringBuffer insert( int offset, int i )
public StringBuffer insert( int offset, long l )
public StringBuffer insert( int offset, float f )
public StringBuffer insert( int offset, double d )
public StringBuffer insert( int offset, String str )
public StringBuffer insert( int offset, char str[] )

将boolean、char、int、long、float、double类型的变量、String类的对象或字符数组插入到StringBuffer类的对象中的第offset个位置。用法如:

StringBuffer sb=new StringBuffer("abfg");
sb.insert(2,"cde");
(注:sb的值为abcdefg)
public int length()

这个方法返回字符串变量的长度,用法与String类的length方法类似。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值