如何在 Java 中列印字串中每個單詞的第一個字元?
String 類可用於表示字串,Java 程式中的所有字串文字都作為 String 類的例項實現。字串是常量,其值一旦建立就不能更改(不可變)。
我們可以使用以下程式列印字串中每個單詞的第一個字元。
示例
public class FirstCharacterPrintTest {
public static void main(String[] args) {
String str = "Welcome To Tutorials Point";
char c[] = str.toCharArray();
System.out.println("The first character of each word: ");
for (int i=0; i < c.length; i++) {
// Logic to implement first character of each word in a string
if(c[i] != ' ' && (i == 0 || c[i-1] == ' ')) {
System.out.println(c[i]);
}
}
}
}
輸出
The first character of each word: W T T P
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP