Java String StringBuffer and StringTokenizer

来源:互联网 发布:如何在mac上安装jdk 编辑:程序博客网 时间:2024/05/16 15:08

String

一个character constant 是char 在unicode character set中的整数值。A String 是String类的实例,定义String有两种形式。

 

String s1 = new String("new String"); //initializes String reference s1 to the new created String Object "new String"

String s2 = "ss";//anonymous java String object

String s3 = "ss";

 

Java treats all annonymous Strings with same contents as on anonymous String object that has many references to conserves memory.Thus s2==s3 is true and s2.equals(s3) is true

 

String Constructors

char charArray[] = new {'b','i','r','t','h','d','a','y'};

byte byteArray[] = new {(byte)'n',(byte)'e',(byte)'w',(byte)'y',(byte)'e',(byte)'a',(byte)'r',};

 

String s,s1,s2,s3.s4.s5.s6.s7;

StringBuffer buffer;

s = new String("Hello");

buffer = new StringBuffer("Hello StringBuffer");

 

s1 = new String();

s2 = new String(s);

//String inistantiates a new String object and assigns it to reference s2,using class String's copy constructor. the new String object contains a copy of the characters in the String object b that is passed as a argument to the constructor.

s3 = new String(charArray); // output is birthday

s4 = new String(byteArray); //output is newyear

s3 = new String(charArray,5,3);// output is day

s4 = new String(byteArray,3,4);//output is year

s4 = new String(buffer); // output is Hello StringBuffer

 

String objects are immutable, their character contents cannot be changed after they are created, any changes to String contents creates a new String Object. The StringBuffer is a dynamically resizable and modifiable string.


String 的方法

因为String是类,所以它有length方法,而不是属性。

String s1 = "123456";

Char[] charArray = new Char[5]

s1.charAt('3');

s1.getChars(0,5,charArray,0); //把s1中的character从0(start index),到5(end index)拷贝到charArray的第0(start index of destination array)位

 

Method equalsStringObject类中继承来的,来测试两个objects的内容是不是相等。比较String时,其实是比较两个String的每一个字符的unicode整数值是不是相等。 == 比较的是两个reference是不是指向同一Object。当==用在primitive data type时,如果比较的值相等则是true, 但如果比较references, 如果都指向同一object in memory 则为真。

 

s1.compareTo(s2): two Strings are compared character by character. 如果想等会返回0,如果s1的一个字符比s2大的话,返回s1的字符的unicode int - s2字符的unicode int =大于0,如果小的话就是负数小于零。

 

s1.regionMatches(0,s2,0,5)  //case sensitive,第一个是s1的starting index,第二个是比较的String object,第三个是s2的start index, 第四个是比较的字符的长度。

s1.regionMatches(true, 0,s2,0,5)//ignore case

regionMatches comare portions of two String objects for equlity.

 

s1.startsWith('st') s1.startsWith('st',2) s1.endsWith('st') s1.endsWith('st',25)

返回值是boolean型,第一个参数是要比较的字符串,第二个字符是index, endsWith从后向前搜查。

 

s1.indexOf("hello") s1.indexOf('h')

if indexOf find the character, it returns the index of that character in the String, otherwise, it returns -1.

s1.indexOf('h'.34) //the second argument indicates the starting index to search in String s1.

 

s1.lastIndexOf('$') s1.lastIndexOf("hello")

从后向前查询

s1.lastIndexOf('h',24)

the second argument indicates the highest index from which to begin searching backward for the character

 

s1.concat(s2) //s2 is appended at the end of String s1

concat方法连接两个String object 并返回一个新的String Object. s1 和s2指向的String object维持不变。不过使用StringBuffer更有效率。

 

char charArray[] = s1.toCharArray();

s1.replace('l','L');

 

String.valueOf(a)把参数a返回成String值。a的类型可以是boolean, char, int, long, float, double and Object.  其中 Object可以是因为它的toString方法。

 

String s1 = new String("hello");

Strings2 = new String("hello");

s3 = s1.intern();

s4 = s2.intern();

 

s3 ==s4 is true

s3==s1 is false

s2==s4is false

s1==s4 is false

因为比较大的String objects会比较慢,使用intern方法可以提高比较速度。s1调用intern方法时,它返回一个指向String object的reference并且这个String Object拥有与s1完全相同的contents. Class String会把这个返回的String Object保存在memory中 during program execution. 如果the program invokes method intern on other String objectswith contents identical to the original String s1, method intern returns a reference to the copy of the String maintained in memory by class String. 这样程序可以用intern方法在很大的String上,程序用==作比较会更快,因为==只是比较references. 用equals会一个字符一个字符的比对String objects内容。

 

StringBuffer

有三个constructor方法,

StringBuffer sb1 = new StringBuffer();   //default size 16

StringBuffer sb1 = new StringBuffer(10); // size 10

StringBuffer sb1 = new StringBuffer("hello"); // defause size is number of characters in the String argumnet + 16

 

length() method returns the number of characters in the StringBuffer

capacity() method returns the number of characters can be strored in the StringBuffer without allocating more memory.

setLength(int i) set the length of String currently stored in the StringBuffer, if the current String length is larger than i, then reduced the original String length to the new length.

setCapacity(int y) set the capacity of the StringBuffer,if the current capacity is more than the specified capacity, the StringBuffer's capacity remain unchanged.

charAt(int k) takes an integer argument and returns the character inthe StringBuffer at that index.

setCharAt(int i, char c) set the character c at the index i. the argument i must be large or equal to 0 and less than the length.

buffer.getChars(int i, int j,char[] charArray, int k). i is the starting index from which characters should be copied in the StringBuffer, the index j past the last character to the copied from the StringBuffer, charArray is the char array which characters are to be copied, k is the first character should be places in the char array.

buffer.reverse()  returns String which is the reverse of the original String buffer.

buffer.insert(0, i) method allows data values to be inserted at any position in a StringBuffer. the type of i can be Object, String, char, boolean, char, int, long, float, double.

buffer.deletaCharAt(int i) delete character at a specified position

buffer.delete(int i, int j) delete from index i to index j.

 

Character type wrapper class. have the following methods

Char c

Character.isDefined(c) //if c is defined in the Unicode character set; return true/false

Character.isDigit(c)      //if c is a digit in Unicode Character set; return true/false

Character.isJavaIdentifierStart(c) //if c is the character that can be used as the first character of an identifier

Character.isJavaIdentifierPart(c)  //if c is a character that can be used in Identifier in Java

Character.isLetter(c)                      //if c is a letter

Character.isLetterOrDigit(c)

Character.isLowerCase(c)

Character..isUpperCase(c)

Character.toUpperCase(c)

Character.toLowerCase(c)

 

Character c = new Character('c')

c.charValue() returns the char value stored in Character c

digit(Char c, int radix) and forDigit(int digit, int radix) perform conversions between characters and digits in different number systems. common number systems include decimal (base10), octal (base 8), hexadecimal (base 16) and binary (base 2). the radix  should be 2,8,10 or 16.

 

Class StringTokenizer

StringTokenizer class  from package java.util. it breaks a string into its component tokens. its delimiters are white space characters such as blank, tab, newline, and carriage return " /n/t/r".

 

StringTokenizer tokens = new StringTokenizer("This is Beijing");

tokens.countTokens();//返回token的数目

while(tokens.hasMoreTokens() )

{

System.out.println(tokens.nextToken());

}

StringTokenizer tokens = new StringTokenizer("This is Beijing",",");//第二个参数设置新的delimiter

StringTokenizer tokens = new StringTokenizer("This is Beijing",",",true);//第二个参数设置新的delimiter,第三个delimiter指示是否把delimiter也当做token。

tokens.nextToken(newDelimiterString) //change the delimiter String while tokenizing a string.

 

原创粉丝点击