Given a string s consisting of words and spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
Example 1:
Input: s = “Hello World” Output: 5 Explanation: The last word is “World” with length 5.
想用空格分離後,在找出最後一個單字的長度
class Solution {
public int lengthOfLastWord(String s) {
if( s!= null & s.length()>0){
String[] temp = s.split(" ");
if (temp != null && temp.length>0){
String last = temp[temp.length-1];
return last.length();
}
}
return 0;
}
}
從最後一個字元開始算,加總字元個數,如果遇到空白就結束,代表已經數完最後一個單字
public static int lengthOfLastWord2(String s) {
int len = 0; //計算最後一個單字的長度
int tail = s.length() - 1; //整個字串的長度
while (tail >= 0 && s.charAt(tail) == ' ') {
tail--; //減去後面的空白
}
//從後面往前算到該字元為空白為止
while (tail >= 0 && s.charAt(tail) != ' ') {
len++;
tail--;
}
return len;
}
1. s.length() 是字串 s 的方法 length() 的調用,用於獲取字串的長度。它會返回一個整數值,表示字串的長度,所以在調用時需要使用括號。
2. temp.length 是陣列 temp 的屬性 length,用於獲取陣列的長度。在Java中,陣列的長度屬性是一個公開的屬性,不需要使用括號。
<補充-字串符分割>
public static void main(String args[]){
String str = "www-hello_world-com";
String[] temp;
String delimeter = "-"; // 指定分割字符
temp = str.split(delimeter); // 分割字符串
for(int i =0; i < temp.length ; i++){
System.out.println(temp[i]);
System.out.println("");
}
String str1 = "www.hello.world.com";
String[] temp1;
String delimeter1 = "\\."; // 指定分割字符(\\.)
temp1 = str1.split(delimeter1); // 分割字符串
for(String x : temp1){
System.out.println(x);
System.out.println("");
}
}
<補充-chatAt()>
public class Main {
public static void main(String args[]) {
String s = "www.helloworld.com";
char find = s.charAt(9);
System.out.println(find);
}
}
->w
*排版快捷鍵: option + command + L