Examples of how arrays and string types are used in Java _java

Source: Internet
Author: User
Tags first string stringbuffer

Java arrays

An array is a set of data that has the same data type. Java supports multiple arrays, each base cell of a one-dimensional array is data of the basic data type, and the two-dimensional array is a one-dimensional array of one-dimensional arrays, and so on, each basic unit of an n-dimensional array is an array of n-1 dimensions that are n-1 arrays. The following is an example of a one-dimensional array to illustrate the use of Java arrays.

1. Array declaration

The array declaration has the following two forms (the square brackets differ in position):

int arr[];
Int[] ARR2;

2, array initialization

There are also two forms of array initialization, as follows (using new or not using new):

int arr[] = new Int[]{1, 3, 5, 7, 9};
Int[] arr2 = {2, 4, 6, 8, 10};

3, traversing the array

The traversal array can be For/foreach, as follows:

 public static void Main (string[] args) {
    int arr[] = new Int[]{1, 3, 5, 7, 9};
    Int[] arr2 = {2, 4, 6, 8, ten};
    for (int i = 0; i < arr.length ++i) {
      System.out.print (Arr[i] + "T");//1 3 5 7 9
    } for
    (int x:arr2) { C7/>system.out.print (x + "T"); 2 4 6 8
    }
  }

4, Arrays.fill () Fill array

Using the static method of the Arrays class, import package java.util.Arrays is required, and many overloaded methods are defined.

void Fill (int[] A, int val) fills all
void Fill (int[] A, int fromindex, int toindex, int val) fills the element of the specified index

 int[] Arr3 = new Int[5];
    for (int x:arr3) {
      System.out.print (x + "T");//0 0 0 0 0 all initialized to 0
    }
    System.out.println ();
    Arrays.fill (ARR3);
    for (int x:arr3) {
      System.out.print (x + "T");//10 10 10 10 10 all filled with the
    System.out.println ();
    Arrays.fill (ARR3, 1, 3, 8);
    for (int x:arr3) {
      System.out.print (x + "T");//10 8 8 10 10 populate the specified index
    }
    System.out.println ();


5, Arrays.sort () array sorting

void sort (int[] a) all sort
void sort (int[] A, int fromindex, int toindex) Sorts the elements of the specified index

 Int[] Arr4 = {3, 7, 2, 1, 9};
    Arrays.sort (ARR4);
    for (int x:arr4) {
      System.out.print (x + "T");//1 2 3 7 9
    }
    System.out.println ();
    Int[] Arr5 = {3, 7, 2, 1, 9};
    Arrays.sort (ARR5, 1, 3);
    for (int x:arr5) {
      System.out.print (x + "T");//3 2 7 1 9
    }
    System.out.println ();

6, arrays.copyof () copy array

Int[] copyof (int[] original, int newlength) to copy the array, specifying the length of the new array
Int[] Copyofrange (int[] original, int from, int to) copies the array, specifying the index of the original array being copied

  Int[] Arr6 = {1, 2, 3, 4, 5};
    int[] arr7 = arrays.copyof (ARR6, 5); 1 2 3 4 5
    int[] arr8 = Arrays.copyofrange (ARR6, 1, 3);//2 3 for
    (int x:arr7) {
      System.out.print (x + "T" );
    }
    System.out.println ();
    for (int x:arr8) {
      System.out.print (x + "T");
    }
    System.out.println ();

Java strings
the Java string type is a string class, and the following describes how to manipulate the string.

1. String connection

string concatenation uses the "+" symbol, as follows:

    string s = new String ("Hello");
    String s2 = new String ("World");
    SYSTEM.OUT.PRINTLN (S + "" + s2); Hello World

2. Get string length

Gets the string length using Str.length (), the following example:

    String s3 = new String ("Hello Java");
    System.out.println (S3.length ()); 10

3, get the index of the specified string

Gets the index of the specified string using Str.indexof (substr), Str.lastindexof (SUBSTR), as follows:

    String S4 = new String ("How are You");
    System.out.println (S4.indexof ("O")); 1 Find
    System.out.println from scratch (s4.lastindexof ("O"));//9 start at the end

4. Get the characters for the specified index

Gets the characters for the specified index using Str.charat (index), as follows:

    String S5 = new String ("Hello Java");
    System.out.println (S5.charat (4)); O

5, remove the space in the string

There are several ways to remove spaces in a string, using Str.trim () or Str.replaceall (regex, replacement), or you can use the StringTokenizer class to separate strings using spaces, Import Package Java.util.StringTokenizer is required before use, as shown in the following example:

 String s6 = new String ("Hello Java");
    String s7 = S6.trim (); Removes the space string
    s8 = S6.replaceall ("" "" ") at the beginning and end of the strings; Replace all spaces in a string
    StringTokenizer st = new StringTokenizer (S6, ""); Use spaces to separate strings
    stringbuffer sb = new StringBuffer ();
    while (St.hasmoretokens ()) {
      sb.append (st.nexttoken ());
    }
    System.out.println ("\" "+ S6 +" \ "+" length = "+ s6.length ()); "Hello Java" length =
    System.out.println ("\" + s7 + "\" + "length =" + s7.length ()); "Hello Java" length = ten
    System.out.println ("\" "+ S8 +" \ "+" length = "+ s8.length ()); "Hellojava" length = 9
    System.out.println ("\" + sb.tostring () + "\" + "length =" + sb.tostring (). Length ()); "Hellojava" Length = 9

6. Replacement string

The replacement string can replace all substrings, or you can replace the first substring, as in the following example:

 string sr = new String ("ABC abd BCD");
    String SR2 = sr.replace ("ab", "xx"); Replace all substrings
    string SR3 = Sr.replacefirst ("ab", "xx");//Replace the first string
    System.out.println (SR2);//"Xxc xxd BCD"
    Syst Em.out.println (SR3); "Xxc adb BCD"

7, string sentence, etc.

There are a number of cases, such as string content judgments, whether to ignore case, memory address, and so on, the beginning or end of the string, and so on, the following example:

  String se = new String ("Summer is so Hot");
    String SE1 = new String ("Summer is so Hot");
    String se2 = new String ("Summer is so Hot");
    String se3 = se;
    System.out.println (SE = = SE1); False comparison of memory rather than string content
    System.out.println (se = = SE3);//True
    System.out.println (Se.equals (SE1));//True Compare string contents
    System.out.println (Se.equals (SE2));//False
    System.out.println (Se.equalsignorecase (SE2)); True ignores case
    System.out.println (Se2.startswith ("Summer"));//True string start
    System.out.println (Se2.endswith ( "Cold")); False String End

8. String Capitalization conversion

String capitalization is converted to the following example:

  String sc = new string ("Hello World");
    String SCL = Sc.tolowercase (); Hello world converts to lowercase
    String SCU = Sc.touppercase ();//Hello World converts to uppercase
    System.out.println (SCL + "" + SCU);

9, String separation

Strings are separated by the following example:

  string ss = new String ("Abc,def,g,h");
    string[] Ss2 = Ss.split (","); Comma-delimited for
    (String x:ss2) {
      System.out.print (x + "T");//ABC def g h
    }

10. Format string

There are several forms of string formatting, such as date formatting, time formatting, conversion, and so on, and the use of the date class requires the import package Java.util.Date, as follows:

    Date d = new Date ();
    System.out.println (d); Wed 16:00:36 CST 2015 default format
    SYSTEM.OUT.PRINTLN (String.Format ("%tm", d));//72-digit month
    System.out.printl N (String.Format ("%th", d)); 162-bit 24-hour
    System.out.println (String.Format ("%x", 256));//1006 System

11, String, StringBuffer, StringBuilder class comparison

String: Strings constants, immutable objects, variable content changes are actually generated a new string object, when the variable content multiple times, frequently changes to the system performance, especially when the GC began to work, the program speed will be slow.

StringBuffer: String variable, thread safe, variable content change is actually the same object to operate, more efficient than string type.

StringBuilder: String variable, compatible with StringBuffer, but not thread-safe, if it is single-threaded, priority to use StringBuilder, it is faster than StringBuffer.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.