1、字符串
String類的substring方法可以從一個較大的字符串中提取一個子串,
public class Test {
public static void main(String[] args) {
String a="hello";
String s=a.substring(0, 3);
System.out.println(s);//結果爲hel
}
}
子串hel的長度爲 3,3-0=3
當一個字符串與一個非字符串進行拼接的時候,後者會轉成字符串。
public class Test {
public static void main(String[] args) {
int age=13;
String a="hello"+age;
System.out.println(a);//結果爲hello13
}
}
2、檢測字符串是否相等
使用equals方法檢測兩個字符串是否相等。
對於表達式s.equals(t),如果字符串s和字符串t相等返回true,否則返回false。
如果不區分大小寫可以使用equalsIgnoreCase方法。
不可以使用==這個方法。這個是判斷兩個字符串是否放在同一個位置。
3、輸入
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String name=in.nextLine();//nextLine方法是輸入一行可能包含空格
System.out.println(name);
}
}
如果想輸入一個單詞以空白符爲分隔符,就調用String name=in.next();
讀取一個整數就調用nextInt()方法
int age=in.nextInt();
讀取浮點數就調用nextDouble()方法
Scanner類定義在
import java.util.*;