[Programmers / JAVA] Level 1 Basic String Handling (12918)
[Programmers / JAVA] Level 1 Basic String Handling (12918)
Complete a function, solution, that checks whether the string s has a length of 4 or 6 and consists only of digits. For example, if s is "a234" it returns False, and if it is "1234" it returns True.
@RWBwritten at 2021-12-16 12:38:44
| Rank | Language Used |
|---|---|
| Level 1 | 🖼️ JAVA |
Complete a function, solution, that checks whether the string s has a length of 4 or 6 and consists only of digits. For example, if s is "a234" it returns False, and if it is "1234" it returns True.
- s is a string of length 1 to 8, inclusive.
| s | return |
|---|---|
| "a234" | false |
| "1234" | true |
Only strings that satisfy all of the following conditions should return true; everything else should return false.
- All characters consist of digits
- The length is 4 characters or 6 characters (not 4 to 6)
This can be solved cleanly using a regular expression. Build a regex, and if the string matches it, return true; otherwise, return false.
- Regex: ^([0-9]{4}|[0-9]{6})$
- [0-9] — a digit
- {4} — 4 characters
- | — OR
- ^ — start of string
- $ — end of string
This is a regex that matches strings that are entirely a 4-digit or 6-digit number.
JAVA
import java.util.regex.Pattern; /** * Basic String Handling class * * @author RWB * @since 2021.12.13 Mon 15:38:26 */ class Solution { /** * Method that returns the answer * * @param s: [String] string * * @return [boolean] the answer */ public boolean solution(String s) { return Pattern.matches("^([0-9]{4}|[0-9]{6})$", s); } }
# Programmers# Algorithm# JAVA# Level 1
