Java 字串
Java 字串
字串用於儲存文字。
String
變數包含由雙引號括起來的字元集合
字串長度
Java 中的 String 實際上是一個物件,它包含可以對字串執行某些操作的方法。例如,字串的長度可以透過 length()
方法找到
示例
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());
更多字串方法
有許多可用的字串方法,例如 toUpperCase()
和 toLowerCase()
示例
String txt = "Hello World";
System.out.println(txt.toUpperCase()); // Outputs "HELLO WORLD"
System.out.println(txt.toLowerCase()); // Outputs "hello world"
在字串中查詢字元
indexOf()
方法返回字串中指定文字(包括空格)第一次出現的**索引**(位置)
示例
String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate")); // Outputs 7
Java 從零開始計數位置。
0 是字串中的第一個位置,1 是第二個,2 是第三個...