blog.itcode.devblog.itcode.dev

[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.

[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.
RWB0104
@RWBwritten at 2021-12-16 12:38:44
Programmers

시리즈 모아보기

Programmers

43 / 78
RankLanguage Used
Level 1

🖼️ JAVA

🔗 Basic String Handling

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.
sreturn
"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
ship
blog.itcode.dev

Notes from the π-th Alpaca

7.0.1
Developed by RWB since 2021.057th upgraded at 2026.08