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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值