Home  >  Article  >  Java  >  Java String Advanced

Java String Advanced

巴扎黑
巴扎黑Original
2017-06-26 11:29:461177browse

Java String Advanced

Preface

There are three most commonly used classes for string operations, namely String, StringBuilder, and StringBuffer, which will be discussed in detail below. Talk about these three classes...

String

The String class represents a string. This is the most basic class for strings. This is also used There are many classes, so I won’t introduce them in detail here

Construction

  • ##new String(String str)

  • new String(StringBuilder str)

  • ##new String(StringBuffer str)

  • new String(byte[] bys,String charsetName)

    Constructs a new String by decoding the specified byte subarray using the specified character set.

Common methods

    ##str charAt(int index)
  • Returns the character at the specified index

  • String concat(String str)
  • Connect the specified string str to the end of this string and return the characters after the connection is successful, so it needs to be accepted to have an effect.

  • boolean contains(CharSequence s)
  • Determine whether this string contains the specified char value sequence. CharSequence here is an interface and its subclasses can be used directly. As parameter (String, StringBuffer, StringBuild)

  • static String copyValueOf(char[] c)
  • Convert character array into string and return

  • static String copyValueOf(char[] c,int off,int count)
  • Convert the intercepted character array into a string and return it. Off is the subscript to start interception, and count is Number of interceptions

  • boolean endWith(String s)
  • Determine whether the string ends with s

  • boolean equals(Object o)
  • Used for comparison

  • int indexOf(char c)
  • Returns the index of the first occurrence of character c in the string

  • int indexOf(char c,int fromIndex)
  • Start searching from the specified index and find the first occurrence of the index

  • int indexOf(String str)
  • Returns the index of the first occurrence of the specified substring in this string.

  • int indexOf(String str,int fromIndex)
  • Returns the index of the first occurrence of the specified substring in this string, starting from the specified index .

  • boolean isEmpty()

  • ##int length()
  • boolean matches(String regex)
  • Whether to match the regular expression
  • trim()
  • Return string A copy of , ignoring leading and trailing whitespace.
  • String substring(int beginIndex)
  • Returns a new string that is a substring of this string.
  • String substring(int beginIndex, int endIndex)
  • Returns a new string that is a substring of this string.
  • String toUpperCase()
  • Converts all characters in this String to uppercase using the rules of the default locale.
  • String[] split(String regex)
  • Split this string based on matches of the given regular expression.
  • String[] split(String regex, int limit)
  • Split this string based on matching the given regular expression.
  • char[] toCharArray()
  • Convert this string to a new character array.
  • byte[] getBytes(Charset charset)
  • Encode this
  • String

    to ## using the given charset #byte sequence and store the result into a new byte arrayNote the new above

The construction method String(byte[] bys,String charsetName) is very important. It can change the encoding set of the string (used in conjunction with byte[] getBytes(Charset charset)). Let's look at an example. The code is as follows:

  • /*         * InputStreamReader实现了将字节流FileInputStream转换为字符流,然后使用转换来的字节流创建高效流,从而实现高效的读写         *//*         * 编码集(我的eclipse编辑器默认的是utf-8         * 下面将中文字符串的编码集变为GBK写入a.txt文件,因为a.txt默认的是utf-8的因此这里在文件中显示的是乱码         * 然后我们读出来的还是GBK的,因为我们写入的是GBK编码集的,但是我的eclipse是utf-8的编码集,因此在控制台上输出的还是乱码         * new String(byte[] bys,String         * charsetName)使用这个构造方法将byte数组改变编码集并且转换为utf-8格式的,那么这次在控制台上输出的就不乱码了         */// 将GBK格式的中文写入a.txt文件File file = new File("src/a.txt");
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            String str = "中";byte[] by = str.getBytes("GBK"); // 将字符串改为GBK编码集fileOutputStream.write(by);
            fileOutputStream.close();        //从a.txt文件中读取中文FileInputStream fileInputStream = new FileInputStream(file);int len;byte[] bys = new byte[4];while ((len = fileInputStream.read(bys)) != -1) {
                System.out.println(new String(bys, "GBK"));
            }
            fileInputStream.close();

  • StringBuffer
Thread-safe mutable character sequence. A string buffer similar to
String

, but cannot be modified. Of course, the most important point is thread safety. We can see from its source code that thread control blocks are used for some operations (

append
,

insert..) To achieve synchronization, it is suitable for use under multi-threading. The source code is as follows:

    public synchronized StringBuffer append(Object obj) {super.append(String.valueOf(obj));return this;
    }public synchronized StringBuffer append(String str) {super.append(str);return this;
    }    public synchronized StringBuffer delete(int start, int end) {super.delete(start, end);return this;
    }/**     * @throws StringIndexOutOfBoundsException {@inheritDoc}     * @since      1.2     */public synchronized StringBuffer deleteCharAt(int index) {super.deleteCharAt(index);return this;
    }
<h3>Construction</h3> <blockquote> <ul class=" list-paddingleft-2"> <li><p>##new StringBuffer(StringBuilder str)<code>

  • ##new StringBuffer(String str)

  • Commonly used methods

      ##StringBuffer append(str)
    • will The str of the specified type is appended to the end of this string (

      String,char,char[],int,double,float,long,StringBuffer,StringBuilder)

    • StringBuffer insert(int offest, str)
    • Insert the str of the specified type into this sequence. offset represents the index of the starting position of insertion. The types include String, char, char[], int, double, float, long,StringBuffer,StringBuilder

    • String delete(int fromIndex,int endIndex)
    • Removes the string in this sequence and returns a new buffer string

    • StringBuffer reverse()
    • Reverse the string

    • String substring(int start)
    • Return a new A String containing the subsequence of characters currently contained by this character sequence.

    • String substring(int start, int end)
    • Returns a new String containing the subsequence of characters currently contained by this sequence.

    • StringBuffer deleteCharAt(int index)
    • Removes the char at the specified position in this sequence.

    • int length()
    • Length

      ##String toString()
    • Returns the data in this sequence string representation of .
    • StringBuilder
    It is recommended to use this class in preference because it is faster than

    StringBuffer

    in most implementations. However, this class is not thread-safe and is only suitable for single threads. If you use multi-threading, it is recommended to use
    StringBuffer

    . Of course, you can also use this, but you need to implement synchronization yourselfConstruction method

    new StringBuilder(String str)
    • Common methods
    The common methods of this class are the same as

    StringBuffer

    , so I won’t list them one by one here. You can use them by referring to the above

    The above is the detailed content of Java String Advanced. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn