浪潮優派培訓java筆記:第7章 String

第7章 String

7.1 基本數據類型

String不可以被繼承,因爲java.lang.String是一個final類。(面試常考)

 

public class TestString{

    public static void main(String[]args) {     

       String s1="Hello";

       String s2="Hello";

       System.out.println(s1==s2);  //true;s1、s2都指向常量區的字符串常量"Hello"

       String s3=new String("hello");

       String s4=new String("hello");

        System.out.println(s3==s4);  //false;s3、s4指向不同的String對象

       System.out.println(s1==s3);  //false

       System.out.println(s3.equals(s4));//true;比較的是所指對象的值而非地址

       System.out.println(s1.equals(s3));//false

    }

}

 

String是值傳遞,StringBuffer是引用傳遞

public class J_Test_4_11 {

    public static void mb_method(Strings, StringBuffer t) {

       s =s.replace('j', 'i');

       t = t.append("C");

    }

    public static void main(String[]args) {

       String a = new String("java");

       StringBufferb = new StringBuffer("java");

       mb_method(a,b);

       System.out.println("a:" + a + " , b:" + b);

    }

}

【運行結果】a:java, b:javaC

public class J_Test_4_13 {

    public static voidmb_method(StringBuffer x, StringBuffer y) {

       x.append(y);

       y = x;  //把x的地址賦給y

    }

    public static void main(String[]args) {

       StringBuffera = new StringBuffer("A");

       StringBufferb = new StringBuffer("B");

       mb_method(a,b);

       System.out.println(a + "," + b);

    }

}

【運行結果】AB,B

 

 

      String類的常用方法(詳情參見幫助文檔)

  int length();//獲取長度

  char charAt(int);//取得指定位置上的字符

  char[] toCharArray();//把指定字符串轉換爲字符數組

  byte[] getBytes(); //轉換爲字節數組

  int compareTo(String);//與另一個字符串按字典順序比較大小,返回值爲>0, =0, <0 三種情況之一

  boolean startsWith(String);//判斷是否以指定的字符串打頭

  boolean endsWith(String);//判斷是否以指定的字符串結尾

  String concat(String);//返回與另一個字符串連接後的字符串

  String substring(intbegin);//可用於字符串截取
String substring(int begin,int end);//返回子串,注意不包括end位置上的字符

  String trim();//返回去除兩端空格後的字符串

  String replace(char oldc,char newc);
String replaceAll(String olds,String news);//返回替換後的字符串

  String toLowerCase();//轉換爲小寫

 StringtoUpperCase(); //轉換爲大寫

  int indexOf(char/String);
int indexOf(char/String,int offset);//返回字符/串首次出現的位置,無時返回-1

  int lastIndexOf(char/String);
int lastIndexOf(char/String,int offset);//返回字符/串末次出現的位置,無時返回-1

  static String valueOf(xxx);//返回xxx的字符串表示,xxx一般取基本數據類型和字符數組
                     //使用它可以實現數字到字符串的轉換

       【String類的常用方法練習】

  字符串t中的字符爲( )

    String s = "hypertext";

    String t = s.substring(2, 5);

    System.out.println(t);

   A. "yper "          B. "ype"       C."pert "      D."per"

答案:D  解析:s.substring(2, 5);//從下標爲2的取到下標爲4的,注意取不到5.

 

輸入一個字符串,顯示將該字符串中非字母字符刪除後的字符串。

public class DeleteStr {

    public static void main(String[]args) {

       String str = "sj$%^&*ASQEkjf_sd/sd[]sd'fds3@s1!";

       String newStr= new String();

       char a[] =str.toCharArray();

       for (int i = 0; i <str.length(); i++) {

           System.out.print(a[i] + " ");

           if (a[i] >= 'a' && a[i]<= 'z' || a[i] >= 'A' && a[i] <= 'Z')

              newStr= newStr.concat(String.valueOf(a[i]));

       }

       System.out.println();

       System.out.println("刪除後的字符串爲:" + newStr);

    }

}

【方法提煉】

1.      將其它類型(如字符串)轉換成字符串形式:String.valueOf(char c);

 

 編寫一個程序,輸出一個字符串中的大寫英文字母數,小寫英文字母數以及非英文字母數。

方法一:

public class CountString {

    public static void main(String[]args) {

       String s = "I love China!Because I'm a Chinese!";

       int k = 0, m = 0, n =0;

       for (int i = 0; i <s.length(); i++) {

           char c = s.charAt(i); //把字符串中的每一個字符賦給字符數組

           if (Character.isUpperCase(c)) //判斷是否是大寫字母(利用包裝類的方法)

              k++;

           else if (Character.isLowerCase(c))

              m++;

           else

              n++;

       }

       System.out.println("大寫字母個數有:" + k + "個");

       System.out.println("小寫字母個數有:" + m + "個");

       System.out.println("非字母個數有:" + n + "個");

    }

}

方法二:

public class CountString {

    public static void main(String[]args) {

       String s = "I love China!Because I'm a Chinese!";

       int k = 0, m = 0, n =0;

       char c[] = s.toCharArray();

       for (int i = 0; i < c.length; i++) {

           if (c[i] >= 65&& c[i] <= 90)

              k++;

           else if (c[i] >= 97&& c[i] <= 122)

              m++;

           else

              n++;

       }

       System.out.println("大寫字母個數有:" + k + "個");

       System.out.println("小寫字母個數有:" + m + "個");

       System.out.println("非字母個數有:" + n + "個");

    }

}

編寫一個程序,輸出在一個字符串中,指定字符串出現的次數。

public class FindStrCount {

    public static void main(String[] args) {

       String str = "I love China!Because I'm a Chinese!";

       String subStr = "Ch";

       int count = 0;

       int index = -1;

       while ((index = str.indexOf(subStr)) != -1) {

           str = str.substring(index +subStr.length());

           System.out.println(str);

           count++;

       }

       System.out.println(count);

    }

}

將取出的字段名轉化爲變量名,例如: COMPANY_CODE==>companyCode

COMPANY_C->companyC*/

public class ChangeStr {

    public static void main(String[]args) {

       String str = "COMPANY_CODE_NAME";

       String newStr= new String();

       String subStr[] = str.split("_");

       for (int i = 0; i <subStr.length; i++) {

           subStr[i]= subStr[i].toLowerCase();

           if (i != 0) {

              subStr[i]= subStr[i].substring(0,1).toUpperCase()

                     +subStr[i].substring(1);

           }

           newStr +=subStr[i];

       }

       System.out.println(newStr);

    }

}

【方法提煉】

1.字符串首字母大寫:str=str.substring(0,1).toUpperCase();

2.去掉字符串的首字母:str=str.substring(1);

3.以下劃線爲界分割字符串並賦給一個字符串數組:String subStr[] = str.split("_");

 

編寫一個方法,返回一個double型二維數組,數組中的元素通過解析字符串參數獲得。如字符串參數:

 "1,2;3,4,5;6,7,8"

 對應的數組爲: d[0,0]=1.0  d[0,1]=2.0 

d[1,0]=3.0  d[1,1]=4.0 d[1,2]=5.0

 d[2,0]=6.0 d[2,1]=7.0  d[2,2]=8.0

public class DoubleStr {

    public static void main(String[]args) {

       String str = "1,2;3,4,5;6,7,8";

       StringsubStr[] = str.split(";");

       double d[][] = new double[subStr.length][];

       for (int i = 0; i <subStr.length; i++) {

           StringsubStr2[] = subStr[i].split(",");

           d[i] = new double[subStr2.length]; //要寫在for內循環外面(難點)

           for (int j = 0; j <subStr2.length; j++) {

              d[i][j]= Double.parseDouble(subStr2[j]);

           }

       }

       for (int i = 0; i < d.length; i++) {

           for (int j = 0; j <d[i].length; j++) {

              System.out.print(d[i][j] + " ");

           }

           System.out.println();

       }

    }

}

【方法提煉】

1.       把字符串轉換成數值類型(包裝類的靜態方法):

double d= Double.parseDouble(str);

 

從輸入的一行字符串中求出其中最長的英文單詞的長度及其個數,並輸出。單詞之間只能用空格隔開。

 【運行示例】

 請輸入以空格隔開的字符串: Nice tomeet you↙

 字符串 = Nice to meet you

 最長單詞長度: 4 ,最長單詞個數: 2

 【編程提示】輸入整行字符串,包括空格符,可以使用Scanner類的nextLine( )方法。*/

import java.util.Scanner;

public class Test {

    public static void main(String[]args) {

       Scanner sc = new Scanner(System.in);

       System.out.println("請輸入一行以空格隔開的字符串:");

       String str =sc.nextLine();

       StringsubStr[] = str.split(" ");

       int max = 0, count =0;

       for (int i = 0; i <subStr.length; i++) {

           if (max <subStr[i].length())

              max =subStr[i].length();

       }

       for (int i = 0; i <subStr.length; i++) {

           if (max == subStr[i].length())

              count++;

       }

       System.out.println("最長單詞長度:" + max + ",最長單詞個數:" + count);

    }

}

求一個字符串中字母出現次數(不算空格)

【運行示例】

字符串 = "The Great Wall of China"

運行結果:T-1 h-2 e-2 G-1 r-1 a-3 t-1 W-1 l-2 o-1 f-1C-1 i-1 n-1

public class CountChar {

    public static void main(String[]args) {

       String str = "The Great Wall of China";

       char sub[] =str.toCharArray();

       for (int i = 0; i < sub.length; i++) {

           int count = 1; //注意對於每一個字母初始化一次count

           for (int j = i + 1; j <sub.length; j++) {

              if (sub[i] == sub[j]){

                  sub[j]= ' ';

                  count++;

              }

              if (sub[i] != ' ' && j == sub.length - 1) //最後一次比較才輸出

                  System.out.print(sub[i] + "-" + count + " ");

           }

       }

    }

}

發佈了40 篇原創文章 · 獲贊 39 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章