Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Snippets] Added String Manipulation Snippets for java #236

Merged
merged 23 commits into from
Jan 30, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
9eb5875
case conversion snippets
Mcbencrafter Jan 18, 2025
93a89b7
ascii/unicode to/from string conversion snippets
Mcbencrafter Jan 18, 2025
d532525
tab/space conversion snippets
Mcbencrafter Jan 18, 2025
aa6683b
palindrome/anagram check snippets
Mcbencrafter Jan 18, 2025
872faf2
counting snippets
Mcbencrafter Jan 18, 2025
7d7d077
normalisation snippets
Mcbencrafter Jan 18, 2025
aa4cd5f
reverse snippets
Mcbencrafter Jan 18, 2025
7832e60
hide/truncate snippets
Mcbencrafter Jan 18, 2025
f5b07b5
slugify snippet
Mcbencrafter Jan 18, 2025
dee9622
password generator snippet
Mcbencrafter Jan 18, 2025
0e1bf3a
text between delimiters extraction snippet
Mcbencrafter Jan 18, 2025
ea96f63
finding snippets
Mcbencrafter Jan 18, 2025
51a63b1
renamed snippet for clarity
Mcbencrafter Jan 18, 2025
f330c02
corrected spaces to tabs snippet
Mcbencrafter Jan 18, 2025
648c6bf
added accidentally removed file
Mcbencrafter Jan 18, 2025
41c0404
tried to fix accidentally removed pre-commit file
Mcbencrafter Jan 18, 2025
abd118f
tried to revert pre commit file
Mcbencrafter Jan 18, 2025
31ec9f8
Tried to restore pre-commit file
Mcbencrafter Jan 18, 2025
b1d436c
Merge branch 'main' into main
Mcbencrafter Jan 18, 2025
e15fc2a
replaced count consonants/vowels with a more generic snippet
Mcbencrafter Jan 19, 2025
12abe5f
Merge branch 'main' of https://github.com/Mcbencrafter/quicksnip
Mcbencrafter Jan 19, 2025
c7b4d83
fixed remove punctuation snippet
Mcbencrafter Jan 19, 2025
9f019a9
reset pre-commit file to origin/main because i messed up
Mcbencrafter Jan 19, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions snippets/java/string-manipulation/ascii-to-string.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
title: Ascii To String
description: Converts a list of ascii numbers into a string
author: Mcbencrafter
tags: string,ascii,encoding,decode,conversion
---

```java
import java.util.List;

public static String asciiToString(List<Integer> asciiCodes) {
StringBuilder text = new StringBuilder();

for (int asciiCode : asciiCodes) {
text.append((char) asciiCode);
}

return text.toString();
}

// Usage:
System.out.println(asciiToString(List.of(104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100))); // "hello world"
```
15 changes: 15 additions & 0 deletions snippets/java/string-manipulation/camelcase-to-snake-case.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
title: camelCase to snake_case
description: Converts a camelCase string into snake_case
author: Mcbencrafter
tags: string,conversion,camel-case,snake-case
---

```java
public static String camelToSnake(String camelCase) {
return camelCase.replaceAll("([a-z])([A-Z])", "$1_$2").toLowerCase();
}

// Usage:
System.out.println(camelToSnake("helloWorld")); // "hello_world"
```
27 changes: 27 additions & 0 deletions snippets/java/string-manipulation/capitalize-words.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
---
title: Capitalize Words
description: Capitalizes the first letter of each word in a string
author: Mcbencrafter
tags: string,capitalize,words
---

```java
public static String capitalizeWords(String text) {
String[] words = text.split("(?<=\\S)(?=\\s+)|(?<=\\s+)(?=\\S)"); // this is needed to preserve spaces (text.split(" ") would remove multiple spaces)
StringBuilder capitalizedText = new StringBuilder();

for (String word : words) {
if (word.trim().isEmpty()) {
capitalizedText.append(word);
continue;
}
capitalizedText.append(Character.toUpperCase(word.charAt(0)))
.append(word.substring(1));
}

return capitalizedText.toString();
}

// Usage:
System.out.println(capitalizeWords("hello world")); // "Hello World"
```
28 changes: 28 additions & 0 deletions snippets/java/string-manipulation/check-anagram.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
title: Check Anagram
description: Checks if two strings are anagrams, meaning they contain the same characters ignoring order, spaces and case sensitivity
author: Mcbencrafter
tags: string,anagram,compare,arrays
---

```java
import java.util.Arrays;

public static boolean isAnagram(String text1, String text2) {
String text1Normalized = text1.replaceAll("\\s+", "");
String text2Normalized = text2.replaceAll("\\s+", "");

if (text1Normalized.length() != text2Normalized.length())
return false;

char[] text1Array = text1Normalized.toCharArray();
char[] text2Array = text2Normalized.toCharArray();
Arrays.sort(text1Array);
Arrays.sort(text2Array);
return Arrays.equals(text1Array, text2Array);
}

// Usage:
System.out.println(isAnagram("listen", "silent")); // true
System.out.println(isAnagram("hello", "world")); // false
```
20 changes: 20 additions & 0 deletions snippets/java/string-manipulation/check-palindrome.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
title: Check Palindrome
description: Checks if a string reads the same backward as forward, ignoring whitespaces and case sensitivity
author: Mcbencrafter
tags: string,palindrome,compare,reverse
---

```java
public static boolean isPalindrome(String text) {
String cleanText = text.toLowerCase().replaceAll("\\s+", "");

return new StringBuilder(cleanText)
.reverse()
.toString()
.equals(cleanText);
}

// Usage:
System.out.println(isPalindrome("A man a plan a canal Panama")); // true
```
27 changes: 27 additions & 0 deletions snippets/java/string-manipulation/count-character-frequency.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
---
title: Count Character Frequency
description: Counts the frequency of each character in a string
author: Mcbencrafter
tags: string,character,frequency,character-frequency
---

```java
public static Map<Character, Integer> characterFrequency(String text, boolean countSpaces, boolean caseSensitive) {
Map<Character, Integer> frequencyMap = new HashMap<>();

for (char character : text.toCharArray()) {
if (character == ' ' && !countSpaces)
continue;

if (!caseSensitive)
character = Character.toLowerCase(character);

frequencyMap.put(character, frequencyMap.getOrDefault(character, 0) + 1);
}

return frequencyMap;
}

// Usage:
System.out.println(characterFrequency("hello world", false, false)); // {r=1, d=1, e=1, w=1, h=1, l=3, o=2}
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
title: Count Character Occurrences
description: Counts the occurrences of the specified characters in a given string
author: Mcbencrafter
tags: string,characters,counter,occurence
---

```java
import java.util.List;

public static int countCharacterOccurrences(String text, List<Character> characters) {
int count = 0;

for (char character : text.toCharArray()) {
if (characters.indexOf(character) == -1)
continue;

count++;
}

return count;
}

// Usage:
System.out.println(countCharacterOccurrences("hello world", List.of('l', 'o'))); // 5
```
15 changes: 15 additions & 0 deletions snippets/java/string-manipulation/count-words.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
title: Count Words
description: Counts the number of words in a string
author: Mcbencrafter
tags: string,word,count
---

```java
public static int countWords(String text) {
return text.split("\\s+").length;
}

// Usage:
System.out.println(countWords("hello world")); // 2
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
title: Extract Text Between Delimiters
description: Extracts a text between two given delimiters from a string
author: Mcbencrafter
tags: string,delimiters,start,end
---

```java
public static String extractBetweenDelimiters(String text, String start, String end) {
int startIndex = text.indexOf(start);
int endIndex = text.indexOf(end, startIndex + start.length());

if (startIndex == -1 || endIndex == -1)
return "";

return text.substring(startIndex + start.length(), endIndex);
}

// Usage:
System.out.println(extractBetweenDelimiters("hello, world!", ",", "!")); // " world"
```
25 changes: 25 additions & 0 deletions snippets/java/string-manipulation/find-longest-word.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
---
title: Find Longest Word
description: Returns the longest word in a string
author: Mcbencrafter
tags: string,length,words
---

```java
public static String findLongestWord(String text) {
String[] words = text.split("\\s+");
String longestWord = words[0];

for (String word : words) {
if (word.length() <= longestWord.length())
continue;

longestWord = word;
}

return longestWord;
}

// Usage:
System.out.println(findLongestWord("hello world123")); // "world123"
```
25 changes: 25 additions & 0 deletions snippets/java/string-manipulation/find-unique-characters.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
---
Title: Find Unique Characters
Description: Returns a set of unique characters from a string, with options to include spaces and control case sensitivity
Author: Mcbencrafter
Tags: string,unique,characters,case-sensitive
---

```java
public static Set<Character> findUniqueCharacters(String text, boolean countSpaces, boolean caseSensitive) {
Set<Character> uniqueCharacters = new TreeSet<>();

for (char character : text.toCharArray()) {
if (character == ' ' && !countSpaces)
continue;
if (!caseSensitive)
character = Character.toLowerCase(character);
uniqueCharacters.add(character);
}

return uniqueCharacters;
}

// Usage:
System.out.println(findUniqueCharacters("hello world", false, true)); // Output: [d, e, h, l, o, r, w]
```
25 changes: 25 additions & 0 deletions snippets/java/string-manipulation/mask-text.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
---
title: Mask Text
description: Masks portions of a string, leaving specific parts at the beginning and end visible while replacing the rest with a specified character
author: Mcbencrafter
tags: string,mask,hide
---

```java
public static String partialMask(String text, int maskLengthStart, int maskLengthEnd, char mask)
if (text == null)
return null;

StringBuilder maskedText = new StringBuilder();
maskedText.append(text, 0, maskLengthStart);

for (int currentChar = maskLengthStart; currentChar < text.length(); currentChar++) {
maskedText.append(mask);
}
maskedText.append(text, text.length() - maskLengthEnd, text.length());
return maskedText.toString();
}

// Usage:
System.out.println(partialMask("1234567890", 4, 2, '*')); // "1234****90"
```
15 changes: 15 additions & 0 deletions snippets/java/string-manipulation/normalize-whitespace.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
title: Normalize Whitespace
description: Replaces consecutive whitespaces with a single space
author: Mcbencrafter
tags: string,whitespace,normalize
---

```java
public static String normalizeWhitespace(String text) {
return text.replaceAll(" {2,}", " ");
}

// Usage:
System.out.println(normalizeWhitespace("hello world")); // "hello world"
```
38 changes: 38 additions & 0 deletions snippets/java/string-manipulation/password-generator.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
---
title: Password Generator
description: Generates a random string with specified length and character set, including options for letters, numbers, and special characters
author: Mcbencrafter
tags: string,password,generator,security,random,token
---

```java
public static String randomString(int length, boolean useLetters, boolean useNumbers, boolean useSpecialCharacters) {
String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String numbers = "0123456789";
String specialCharacters = "!@#$%^&*()_+-=[]{}|;:,.<>?";

String allowedCharacters = "";

if (useLetters)
allowedCharacters += characters;

if (useNumbers)
allowedCharacters += numbers;

if (useSpecialCharacters)
allowedCharacters += specialCharacters;

SecureRandom random = new SecureRandom();
StringBuilder result = new StringBuilder(length);

for (int i = 0; i < length; i++) {
int index = random.nextInt(allowedCharacters.length());
result.append(allowedCharacters.charAt(index));
}

return result.toString();
}

// Usage:
System.out.println(randomString(10, true, true, false)); // Random string containing letters, numbers but no special characters with 10 characters
```
15 changes: 15 additions & 0 deletions snippets/java/string-manipulation/remove-punctuation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
title: Remove Punctuation
description: Removes punctuation (, . !) from a string
author: Mcbencrafter
tags: string,punctuation,clean,normalization
---

```java
public static String removePunctuation(String text) {
return text.replaceAll("[,!.?;:]", "");
}

// Usage:
System.out.println(removePunctuation("hello, world!")); // "hello world"
```
15 changes: 15 additions & 0 deletions snippets/java/string-manipulation/remove-special-characters.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
title: Remove Special Characters
description: Removes any character which is not alphabetic (A-Z, a-z) or numeric (0-9)
author: Mcbencrafter
tags: string,special-characters,clean,normalization
---

```java
public static String removeSpecialCharacters(String text) {
return text.replaceAll("[^a-zA-Z0-9]", "");
}

// Usage:
System.out.println(removeSpecialCharacters("hello, world!#%")); // "hello world"
```
Loading
Loading