Java Tutorial/Data Type/String

Материал из Java эксперт
Перейти к: навигация, поиск

Arrays of Strings: Declare an array of String objects where the initial values determine the size of the array

public class MainClass {
  public static void main(String[] arg) {
    String[] colors = {"red", "orange", "yellow", "green", "blue", "indigo", "violet"};
    
    for(String s: colors){
      System.out.println(s);
      
    }
  }
}



red
orange
yellow
green
blue
indigo
violet


Arrays of Strings: using "new" operator

public class MainClass {
  public static void main(String[] arg) {
    String[] names = new String[5];
    
    names[0] = "qwert";
    names[1] = "yuiop";
    names[2] = "asdfg";
    names[3] = "hjkl";
    names[4] = "zxcvb";
    
    System.out.println(names[4]);
  }
}





Assign String variable to null

The literal null is an object reference value that does not refer to anything.



public class MainClass {
  public static void main(String[] arg) {
    String s = null;
    
    System.out.println(s);
  }
}





A string can be compared with a StringBuffer

public class Main {
  public static void main(String[] argv) throws Exception {
    String s1 = "s1";
    StringBuffer sbuf = new StringBuffer("a");
    boolean b = s1.contentEquals(sbuf); 
  }
}





Attempts to use string variable before it has been initialized

public class MainClass {
  public static void main(String[] arg) {
    String s = null;
    
    System.out.println(s.length());
  }
}



Exception in thread "main" java.lang.NullPointerException
	at MainClass.main(MainClass.java:6)


Comparing Two Strings

public class MainClass {
  public static void main(String[] args) {
    String s1 = "Java";
    String s2 = "Java";
    if (s1.equals(s2)) {
      System.out.println("==");
    }
  }
}





Create String with char array

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
public class StringDemo {
  public static void main(String[] args) {
    String palindrome = "Dot saw I was Tod";
    int len = palindrome.length();
    char[] tempCharArray = new char[len];
    char[] charArray = new char[len];
    // put original string in an array of chars
    for (int i = 0; i < len; i++) {
      tempCharArray[i] = palindrome.charAt(i);
    }
    // reverse array of chars
    for (int j = 0; j < len; j++) {
      charArray[j] = tempCharArray[len - 1 - j];
    }
    String reversePalindrome = new String(charArray);
    System.out.println(reversePalindrome);
  }
}





Demo for escape

public class MainClass{
   public static void main(String[] a){
   
       String s = "John \"The Great\" Monroe";
   }
}





Demonstrate toUpperCase() and toLowerCase().

class ChangeCase {
  public static void main(String args[])
  {
    String s = "This is a test.";
   
    System.out.println("Original: " + s);
   
    String upper = s.toUpperCase();
    String lower = s.toLowerCase();
   
    System.out.println("Uppercase: " + upper);
    System.out.println("Lowercase: " + lower);
  }
}





Get InputStream from a String

import java.io.ByteArrayInputStream;
public class Main {
  public static void main(String[] argv) throws Exception {
    byte[] bytes = "asdf".getBytes("UTF8");
    new ByteArrayInputStream(bytes);
  }
}





Length of a string

public class Main {
  public static void main(String[] args) {
    String name = "Java";
    int length = name.length();
    System.out.println("Length = " + length);
  }
}





Remove a character at a specified position using String.substring

public class Main {
  public static void main(String args[]) {
    String str = "this is a test";
    System.out.println(removeCharAt(str, 3));
  }
  public static String removeCharAt(String s, int pos) {
    return s.substring(0, pos) + s.substring(pos + 1);
  }
}





Remove leading and trailing white space from string

public class Main {
  public static void main(String[] args) {
    String text = "     t     ";
    System.out.println("Result: " + text.trim());
  }
}





String class constructors

public class MainClass 
{
   public static void main( String args[] )
   {
      char charArray[] = { "b", "i", "r", "t", "h", " ", "d", "a", "y" };
      String s = new String( "hello" );
      // use String constructors
      String s1 = new String();
      String s2 = new String( s );
      String s3 = new String( charArray );
      String s4 = new String( charArray, 6, 3 );
      System.out.printf("s1 = %s\ns2 = %s\ns3 = %s\ns4 = %s\n", 
         s1, s2, s3, s4 );
   }
}



s1 = 
s2 = hello
s3 = birth day
s4 = day


String class substring methods

public class MainClass
{
   public static void main( String args[] )
   {
      String letters = "abcdefghijklmabcdefghijklm";
      // test substring methods
      System.out.printf( "Substring from index 20 to end is \"%s\"\n",
         letters.substring( 20 ) );
      System.out.printf( "%s \"%s\"\n", 
         "Substring from index 3 up to, but not including 6 is",
         letters.substring( 3, 6 ) );
   } // end main
}



Substring from index 20 to end is "hijklm"
Substring from index 3 up to, but not including 6 is "def"


String Concatenation

public class MainClass
{
   public static void main( String args[] )
   {
      String s1 = new String( "Happy " );
      String s2 = new String( "Birthday" );
      System.out.printf( "s1 = %s\ns2 = %s\n\n",s1, s2 );
      System.out.printf( 
         "Result of s1.concat( s2 ) = %s\n", s1.concat( s2 ) );
      System.out.printf( "s1 after concatenation = %s\n", s1 );
   } // end main
}



s1 = Happy 
s2 = Birthday
Result of s1.concat( s2 ) = Happy Birthday
s1 after concatenation = Happy


String HashCode

public class MainClass {
  public static void main(String[] args) {
    System.out.println("Hello".hashCode());
    System.out.println("Hello".hashCode());
  }
}
/**/



69609650
69609650


String Literals

You can compose long string literals by using the plus sign to concatenate two string literals.



public class MainClass {
  public static void main(String[] a) {
    String s1 = "1 " + "2";
    String s2 = s1 + " = 3";
    System.out.println(s1);
    System.out.println(s2);
  }
}



1 2
1 2 = 3


toLowerCase and toUpperCase

public class MainClass
{
   public static void main( String args[] )
   {
      String s1 = new String( "hello" );
      String s2 = new String( "GOODBYE" );
      String s3 = new String( "   spaces   " );
      System.out.printf( "s1 = %s\ns2 = %s\ns3 = %s\n\n", s1, s2, s3 );
      // test toLowerCase and toUpperCase
      System.out.printf( "s1.toUpperCase() = %s\n", s1.toUpperCase() );
      System.out.printf( "s2.toLowerCase() = %s\n\n", s2.toLowerCase() );
   }
}



s1 = hello
s2 = GOODBYE
s3 =    spaces   
s1.toUpperCase() = HELLO
s2.toLowerCase() = goodbye


To remove a character

public class Main {
  public static void main(String args[]) {
    String str = "this is a test";
    
    System.out.println(removeChar(str,"s"));
  }
  public static String removeChar(String s, char c) {
    String r = "";
    for (int i = 0; i < s.length(); i++) {
      if (s.charAt(i) != c)
        r += s.charAt(i);
    }
    return r;
  }
}
//thi i a tet





Using String class

  1. In Java, ordinary strings are objects of the class String.
  2. A String object represents a string, i.e. a piece of text.
  3. String is a sequence of Unicode characters.
  4. A string literal is a sequence of characters between double quotes.
  5. String objects are immutable.


Using trim() to process commands.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class UseTrim {
  public static void main(String args[]) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String str;
    System.out.println("Enter "stop" to quit.");
    System.out.println("Enter letter: ");
    do {
      str = br.readLine();
      str = str.trim();
      if (str.equals("I"))
        System.out.println("I");
      else if (str.equals("M"))
        System.out.println("M");
      else if (str.equals("C"))
        System.out.println("C.");
      else if (str.equals("W"))
        System.out.println("W");
    } while (!str.equals("stop"));
  }
}