使用 Java Stream API 統計字串中給定字元的出現次數
簡介
在本教程中,我們將實現一種方法,使用 Java 中的 Stream API 統計特定字元在一個字串中出現的次數。字串是字元的集合,我們將使用 String 類的方法來分離字串字元。
我們將接收一個輸入字串,並定義要計數的字元。此方法中使用的函式是 String 類的 chars() 方法和 Stream 介面的 filter() 方法。
char() = 它是 String 類的一個例項方法。它返回 intstream 值。該流包含字串中字元的程式碼點值。
filter() = 用於考慮預測值。它有助於選擇所需的數值流。
Java 中的 Stream API 是在 Java 8 中引入的,它是一組類和物件。此方法簡化了物件處理過程,並提高了程式碼的可讀性。它透過其各種方法和管道流程,為 Java 程式設計師提供了處理複雜任務的靈活性。
示例 1
String = “tutorialspoint” Character = t
輸出
字元“t”在輸入字串中出現 4 次。
在上面的示例中,輸入字串為“tutorialspoint”。任務是計算字元“t”在輸入字串中出現的次數。我們可以看到,“t”在字串中出現了 4 次。
示例 2
String = “Helloworld” Character = “e”
輸出
= 1
在上面的示例中,輸入字串為“Helloworld”,字元為“e”。任務是計算字元“e”在字串中的重複次數。“e”在輸入字串中只出現 1 次。
chars().filter() − 它是 String 類庫函式,返回引數字串的字元值流。filter() 方法與它一起限制不需要的字元流。
string_name.chars().filter()
count() − 它計算流字元並返回它們的個數。呼叫 Java Stream 介面的 count() 方法後,將無法訪問該流。
long count()
演算法
獲取輸入字串。
定義所需的字元並查詢其在輸入字串中的出現次數。
使用 Stream API 的 filter() 方法去除不匹配的字元。
使用 String 類的 chars() 方法將字串轉換為字元。
列印輸出。
邏輯示例 1
我們將使用 Java 實現上述示例,輸入字串為“tutorialspoint”,並計算字元“t”的出現次數。為了實現此示例,我們將使用一些列出的庫函式:
import java.util.stream.*; public class GFG { // Method that returns the count of the given // character in the string public static long count(String st, char chr){ return st.chars().filter(ch -> ch == chr).count(); } // Driver method public static void main(String args[]){ String st = "tutorialspoint"; char ch = 't'; System.out.println("The occurrence of t in the string is:"); System.out.println(count(st, ch)); } }
輸出
The occurrence of t in the string is: 3
邏輯示例 2
import java.util.stream.IntStream; public class CharacterCounter{ public static void main(String[] args) { String s = "Hello, World!"; char c = 'o'; long cnt = countOccurrences(s, c); System.out.println("Occurrences of '" + c + "': " + cnt); } public static long countOccurrences(String s, char c){ return s.chars().filter(ch -> ch == c).count(); } }
輸出
Occurrence of ‘o’ : 2
結論
在本教程中,我們學習了 Java 中的流處理。我們編寫了程式碼和兩種邏輯來查詢輸入字串中的特定字元。我們使用了 chars() 和 filter() 方法來實現示例,以查詢給定字串中特定字元的出現次數。
Stream 類的 filter() 方法過濾掉輸入字串中不需要的字元。String 類的 chars() 方法將輸入字串分割成字元。