java字符串string
格式:
首先:初始化样例 :String str = “Geeks”;
Creating a String
There are two ways to create string in Java:(两种方式)
String literal\
String s = “GeeksforGeeks”;
Using *new* keyword
String s = new String (“GeeksforGeeks”);
字符串背后的一些事情:
String 字符串是由字符数组(char array)所支持。
Strings in Java are Objects that are backed internally by a char array.
而我们知道,字符数组的大小是固定的,所以:当String发生大小变化时就会产生一个新的String。
那么他是怎样变化的呢?
Whenever a String Object is created, two objects will be created- one in the Heap Area and one in the String constant pool and the String object reference always points to heap area object.
当一个字符串产生的时候,就会创建两个String对象,一个在堆区域,另一个在字符串常态池中,而且字符串引用总指向堆区域的对象。
例如:(看是该字符串引用总是指向堆区域的对象,而且是首字母,像指针一样,不过java避开了指针的概念。)
接口和类在字符串中:
CharBuffer: This class implements the CharSequence interface. This class is used to allow character buffers to be used in place of CharSequences. An example of such usage is the regular-expression package java.util.regex.
不懂CharBuffer:此类实现CharSequence接口。 此类用于允许使用字符缓冲区代替CharSequences。 正则表达式包java.util.regex是这种用法的一个示例。
String: String is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once created.(String的对象是不可改变的)
StringBuffer: StringBuffer is a peer class of String that provides much of the functionality of strings. String represents fixed-length, immutable character sequences while StringBuffer represents growable and writable character sequences.(又出来个String buffer,批判了String的固定长度和不可变后,称自己是可增长的,可变化的。它还是String的同级字符串类。。。)
Syntax:
StringBuffer s = new StringBuffer("GeeksforGeeks");
StringBuilder: The StringBuilder in Java represents a mutable sequence of characters. Since the String Class in Java creates and immutable sequence of characters, the StringBuilder class provides an alternate to String Class, as it creates a mutable sequence of characters.(又来一个StringBuilder 说自己也是可变的字符串
Syntax:
StringBuilder str = new StringBuilder(); str.append("GFG");
StringTokenizer: StringTokenizer class in Java is used to break a string into tokens. Example:
A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations advance this current position past the characters processed. A token is returned by taking a substring of the string that was used to create the StringTokenizer object.(用于处理过的字符串,不太懂)
StringJoiner: StringJoiner is a class in java.util package which is used to construct a sequence of characters(strings) separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix. Though this can also be with the help of StringBuilder class to append delimiter after each string, StringJoiner provides an easy way to do that without much code to write.(也是处理分隔符的,和上面的是一对儿)
Syntax:
public StringJoiner(CharSequence delimiter)
more:
此外,在我们要去取值的时候,比如String第二个字符的值的时候,应该用:
String str = "hello word";
char mychar = str.charAt(1);
如果想要比较字符串的值是否相同的话:
if(s.contentEquals(“-1”))来比较。否则就是比较储存位置(因为String在java中是对象,不是基本类型)