Java Basics Part 13/20 - Strings Class

Java Basics Part 13/20 - Strings Class

目录


在 Java 程序中被广泛使用的 Strings,也就是字符串,本质上是 一串字符序列。在 Java 中,strings 是对象。
Java 平台提供了 String 类来创建和操作 strings。


创建 Strings

最直接的方法:

String greeting = "Hello World!";

同样,既然 strings 是对象,那么就可以使用 new 关键字和构造器来创建一个 String 对象。

public class StringDemo{

   public static void main(String args[]){
      char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
      String helloString = new String(helloArray);  
      System.out.println( helloString );
   }
}

// output
hello.

String 类是不可变的,一旦创建无法改变。如果需要对 字符串 做很大的修改,那么应该使用 StringBuffer 和 StringBuilder 类(StringBuffer 线程安全,所以效率也就更低)。


字符串长度

length() 会返回字符串的长度。

public class StringDemo {

   public static void main(String args[]) {
      String palindrome = "Dot saw I was Tod";
      int len = palindrome.length();
      System.out.println( "String Length is : " + len );
   }
}

// output
String Length is : 17

连接字符串

可以使用 concat() 方法,也可以使用 + 操作符。


创建格式化的字符串

可以使用 format() 来创建格式化的字符串,返回的是一个 String 对象,而不是 PrintStream 对象。

String fs;
fs = String.format("The value of the float variable is " +
                   "%f, while the value of the integer " +
                   "variable is %d, and the string " +
                   "is %s", floatVar, intVar, stringVar);
System.out.println(fs);

String 的方法

请参考 Java Doc 中的 String API。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章