Skip to content

Commit 872faf2

Browse files
committed
counting snippets
1 parent aa6683b commit 872faf2

File tree

4 files changed

+92
-0
lines changed

4 files changed

+92
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
---
2+
title: Count Character Frequency
3+
description: Counts the frequency of each character in a string
4+
author: Mcbencrafter
5+
tags: string,character,frequency,character-frequency
6+
---
7+
8+
```java
9+
public static Map<Character, Integer> characterFrequency(String text, boolean countSpaces, boolean caseSensitive) {
10+
Map<Character, Integer> frequencyMap = new HashMap<>();
11+
12+
for (char character : text.toCharArray()) {
13+
if (character == ' ' && !countSpaces)
14+
continue;
15+
16+
if (!caseSensitive)
17+
character = Character.toLowerCase(character);
18+
19+
frequencyMap.put(character, frequencyMap.getOrDefault(character, 0) + 1);
20+
}
21+
22+
return frequencyMap;
23+
}
24+
25+
// Usage:
26+
System.out.println(characterFrequency("hello world", false, false)); // {r=1, d=1, e=1, w=1, h=1, l=3, o=2}
27+
```
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
---
2+
title: Count Consonants
3+
description: Counts the consonants (every character except for a, e, i, o, u) in a string
4+
author: Mcbencrafter
5+
tags: string,consonants,counter
6+
---
7+
8+
```java
9+
public static int countConsonants(String text) {
10+
String consonants = "bcdfghjklmnpqrstvwxyz";
11+
int count = 0;
12+
13+
for (char character : text.toLowerCase().toCharArray()) {
14+
if (consonants.indexOf(character) == -1)
15+
continue;
16+
17+
count++;
18+
}
19+
20+
return count;
21+
}
22+
23+
// Usage:
24+
System.out.println(countConsonants("hello world")); // 7
25+
```
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
---
2+
title: Count Vowels
3+
description: Counts the vowels (a, e, i, o, u) in a string
4+
author: Mcbencrafter
5+
tags: string,vowels,counter
6+
---
7+
8+
```java
9+
public static int countVowels(String text) {
10+
String vowels = "aeiou";
11+
int count = 0;
12+
13+
for (char character : text.toLowerCase().toCharArray()) {
14+
if (vowels.indexOf(character) == -1)
15+
continue;
16+
17+
count++;
18+
}
19+
20+
return count;
21+
}
22+
23+
// Usage:
24+
System.out.println(countVowels("hello world")); // 3
25+
```
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
title: Count Words
3+
description: Counts the number of words in a string
4+
author: Mcbencrafter
5+
tags: string,word,count
6+
---
7+
8+
```java
9+
public static int countWords(String text) {
10+
return text.split("\\s+").length;
11+
}
12+
13+
// Usage:
14+
System.out.println(countWords("hello world")); // 2
15+
```

0 commit comments

Comments
 (0)