Tag:java String 自己动手写String
Article From:https://www.cnblogs.com/shizongger/p/9124172.html

It was very early to make a wheel. It was said that the programmer who did not want to make wheels was not a good programmer, and used the many open source projects that used Apache, but did not read the open source code. After reading several articles selling anxiety recently, I suddenly became nervous, so I seldom opened my JDK for the first time in my busy schedule.Source code package. First reading: obscure, more than 3 thousand lines of code, all English annotations, some strange grammar and calling strange classes are enough to scare away a middle-aged programmer. Again: just read the outline, this String.class is also annotated and written much more, the core code is not much. Three reading: WowThe entire String class core variable is a char[] array.

private final char value[];

All operations are the value[] core variable to splice concat (), intercept subString (), to determine if there is indexOf (), startWith (). Slow down: when I think of this, I seem to remember something familiar when I was in University.Curriculum, yes, that is, data structure and algorithm, this door is fading away, fading away, slowly fading out of my world, it seems to come in handy again. To tell you the truth, when I was in college, I only learned a semester’s data structure, which was described and implemented in C language. This course was abandoned when I finished my exams.From then on, I thought it would not be used again. But today I want to realize a class of String, and have to recollection. It’s good that although I’m getting into the middle age uncle, it’s still some memory, so it writes and writes the basic methods of String, because of the family JD.K already has a perfect version of the String class. It’s called MyString itself. All you need to know is to operate the ArrayList that is analogous to the data structure. After all, String’s content implementation is an array.
Well, I know what you want to say is: Takl is clean, Show me the Code, go straight to the code!

import java.io.Serializable;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collections;
import java.util.Locale;

public class MyString implements Serializable, Comparable<String>, CharSequence {
    
    private static final long serialVersionUID = -204188373852348874L;
    
    /**
     * Define the char array, the core variable* * /Private final char[] value;/ * * * * ** empty constructor* * /PublicMyString () {Value = new char[0];}/ * * * * ** the construction method of the default String value of @param str*/Public MyString (String STR) {This.value = str.toCharArray ();}Public MyString (char[] value) {This.value = value;}Public MyString (byte[] bytes) {This.value = new char[bytes.length];For (int i = 0; I < bytes.length; i++) {This.value[i] = (char) bytes[i];}}Public MyString (char value[], int offset,Int count) {If (offset < 0) {Throw new StringIndexOutOfBoundsException (offseT);}If (count < = 0) {If (count < 0) {Throw new STringIndexOutOfBoundsException (count);}If (offset < = value.length) {This.value = new char[0];Return;}}If (ofFset > value.length-count) {Throw new StringIndexOutOfBoundsException (offset);}This.value = Arrays.copyOfRange (value, offset, count);}@OverridePuBlic int length () {Return value.length;}@OverridePublic char charAt (int ind)Ex) {If (index > this.value.length index < 0) {Throw new StringIndexOuTOfBoundsException (index);}Return this.value[index];}@OverridePublIC CharSequence subSequence (int start, int end) {If (start < 0) {Throw new STringIndexOutOfBoundsException (start);}If (end > value.length) {ThrOw new StringIndexOutOfBoundsException (end);}If (start > end) {ThroW New StringIndexOutOfBoundsException ("start index is bigger than end index.");}MyString result = new MyString (Arrays.copyOfRange (value, start, end));Return result;}@OverridePublic int compareTo (String o) {Return 0;}Public INT compareTo (MyString anotherString) {If (this = = anotherString) {Return 0;}Return 0;}@OverridePublic String toString () {ReTurn new String (this.value);}Public Boolean equals (Object anObject) {If (this= = = anObject) {Return true;}If (anObject instanceof MyString) {MyString anString = (MyString) anObject;If (anString.length () = = = value.length) {Char[] V1 = anString.value;Char[] V2 = value;Int n =V1.length;While (n--! = 0) {If (v1[n]! = v2[n]) {Return false;}}Return true;}}Return false;}//TODOPublic Boolean contains (CharSequenCE s) {Return true;}Public int indexOf (int CH) {Return indExOf (0, CH);}Public int indexOf (int ch, int fromIndex) {For (int i = 0; I <Value.length; i++) {If (value[i] = = CH) {Return I;}}Return -1;}Public int indexOf (MyString STR) {Return indexOf (STR, 0);}Public int indexOf (MyString STR, int fromIndex) {Char[] source = value;Char[] target = str.value;For (int i = fromIndex; I < source.length; i++) {If (source[i] = = target[0]) {Int index = I;Int sameLen = 1;For (int j = 1; J < target.length & & (i+j) < source.length; i+j) {If (target[j]! = source[i+j]) {Break;}SameLen++;}If (sameLen = = target.length) {Return index;}}}Return -1;}Public MyString concat (MyString STR) {If (str.length () = = 0) {Return this;}Int len = value.length;Int otherLen = str.length ();Char[] buf = ArrAys.copyOf (value, len + otherLen); / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /System.arraycopy (str.value, 0, buf, len, otherLen);Return new MyString (buf);}PubliC Boolean startsWith (MyString prefix) {Return this.startsWith (prefix, 0);}/ *** detect whether a string begins with a substring* @param prefix substring* the starting position of the @param toffset string* @return {@code true} if the string begins with this substring, it returns true; {@code false} otherwise returns false..* @since 1* @author SpringCHang* * /Public Boolean startsWith (MyString prefix, int toffset) {Char[] target = PRefix.value;Char[] source = value;Int sameLen = 0; / / same character lengthFor (int i = 0;I < target.length & & (toffset+i) < source.length; i++) {If (source[toffseT+i]! = target[i]) {Break;}SameLen++;}IF (sameLen = = target.length) {Return true;}Return false;}Public MyString toLowerCase () {Return this.toLowerCase (Locale.getDefault ());}PubLIC MyString toLowerCase (Locale locale) {If (locale = = null) {Throw new NullPoiNterException ();}Char[] newString = new char[value.length];For (int i = 0;I < value.length; i++) {If (value[i] > ='A'& & value[i] < ='Z') {NewString[i] = (char) (value[i] + 32);} else {NewString[i]= value[i];}}Return new MyString (newString);}Public MyString toUpperCase () {Return this.toUpperCase (Locale.getDefault ());}Public MyString toUpperCase (Locale locale) {If (locale = = null) {Throw newNullPointerException ();}Char[] newString = new char[value.length];For (inT i = 0; I < value.length; i++) {If (value[i] > ='a'& & value[i] < ='z') {NewString[i] = (char) (value[i] - 32);} else {NewSTring[i] = value[i];}}Return new MyString (newString);}Public MyString substring (int beginIndex) {If (beginIndex < 0) {Throw new StringIndexOutOfBoundsException (beginIndex);}Return beginIndex==0? This:new MyString (value, beginIndex, value.length-beginIndex);}Public MyString substrinG (int beginIndex, int endIndex) {If (beginIndex < 0) {Throw new StringIndexOuTOfBoundsException (beginIndex);}If (endIndex > value.length) {ThrowNew StringIndexOutOfBoundsException (endIndex);}Return beginIndex==0? This:new MyStRing (value, beginIndex, endIndex);}/ * * * * ** convert a string into an array of characters* @return new character array, can't be the originalOtherwise, users can manipulate and modify String content, which is against String final design principles.* * /Public char[] toCharArray () {//rEturn this.value; can't return directly like thisChar[] charArr = new char[value.length];System.arraycopy(value, 0, charArr, 0, value.length);Return charArr;}}

The appeal is only a mini version of the String class that implements the basic operating function of the String, and does not fully implement all the functions of the String. The wheel does not want to replace the JDK String with it in the project development, just to know what the other’s wheel isBuilt, I know you’re wondering if it’s really able to use it. Here’s the two test class code, and see the output of JDK’s String and the handwritten MyString class.

Test several methods for JDK to bring String.

public class TestJDKString {

    public static void main(String[] args) {
        String str1 = new String("Hello Java,");
        String str2 = new String("Hello Java,");
        System.out.println("str1 str2 Is the address equal? + + (STR1 = = STR2); / / equal sign determines whether the string is equal.System.out.println ("STR1 STR2 content is equal?" + (STR1).equals (STR2)); / / judge whether the string contents are equal.String str3 = new String ("Hello World,");SYstem.out.println (str3.concat (STR1)); / / string concatenationSystem.out.println (str3.concat (STR1).Concat (st)R2)); / / String continuous splicingSystem.out.println (str3.startsWith ("Hello")); / / judge whether the string has Hello.System.out.println (str3.startsWith ("Hello1")); / / judge whether the string has been developed by Hello1.System.out.Println (New String ("string lowercase: I am a Java Programmer. I Love Java") Love ()); / / String lowercase.SyStem.out.println (New String ("string bigger write: I am a Java Programmer. I Love Java") Love ()); / / String uppercase.}}

Output results:

str1 str2 Is the address equal? FalseIs the content of STR1 STR2 equal? TrueHello World, Hello Java,Hello World, Hello Java, Hello Java,TrueFALSEString to be lowercase: I am a Java programmer. I love JavaString writing: I AM A JAVA PROGRAMMER. I LOVE JAVA

Several methods of testing your own handwritten MyString class.

public class TestMyString {

    public static void main(String[] args) {
        MyString str1 = new MyString("Hello Java,");
        MyString str2 = new MyString("Hello Java,");
        System.out.println("str1 str2 Is the address equal? + + (STR1 = = STR2); / / equal sign determines whether the string is equal.System.out.println ("STR1 STR2 content is equal?" + (STR1).equals (STR2)); / / judge whether the string contents are equal.MyString str3 = new MyString ("Hello World,");System.out.println (str3.concat (STR1)); / / string concatenationSystem.out.println (str3.concat (STR1).ConcaT (STR2)); / / String continuous splicingSystem.out.println (str3.startsWith (New MyString ("Hello"))); / / judgmentWhether the string has already started with HelloSystem.out.println (str3.startsWith (New MyString ("Hello1"))); / / judge whether the string has been Hello.1 developmentSystem.out.println (New MyString ("string lowercase: I am a Java Programmer. I Love"Java ").ToLowerCase ())); / / string change lowercaseSystem.out.println (New MyString ("string writing" I am a Java Progra)Mmer. I Love Java "".ToUpperCase ()); / / String uppercase "}}

Output results:

str1 str2 Is the address equal? FalseIs the content of STR1 STR2 equal? TrueHello World, Hello Java,Hello World, Hello Java, Hello Java,TrueFALSEString to be lowercase: I am a Java programmer. I love JavaString writing: I AM A JAVA PROGRAMMER. I LOVE JAVA

Leave a Reply

Your email address will not be published. Required fields are marked *