{ }codelper
string lengthP0341

Characters left in a message with Korean text

One text message can hold up to m characters. The first line gives m, and the second line gives the message that was written. The message is made of Korean letters (Hangul), English letters, digits, punctuation (.
, !
?) and spaces. The number of characters is what you get by counting the visible characters one by one. One Hangul letter, one English letter and one space each count as one character. For example, "안녕 hi" has 5 characters. Print m minus the number of characters in the message. A positive value means that many more characters fit, 0 means the message fits exactly, and a negative value means it is that many characters too long. When it is too long, write the minus sign, as in -3.

Input
1 ≤ m ≤ 1,000 (given as digits only, without a comma).
The message is 1 to 200 characters long and does not start or end with a space.
Hangul appears only as complete syllables from '가' to '힣' (no separate jamo such as ㄱ or ㅏ, and no emoji).
The input is encoded in UTF-8
Output
One line with m minus the number of characters in the message
Example 1 · stdin
10
안녕 hi
stdout
5
Example 2 · stdin
5
코델퍼 최고!!
stdout
-3
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

You ask for the length of a string with Python len(s), JS/TS s.length, Java s.length(), C# s.Length, C strlen(s), C++ s.size() and Craykon s.Length.
But they count in different units.
Python counts characters (code points).
JS, TS, Java, C# and Craykon count UTF-16 units, and one Hangul syllable is one unit, so in this problem that equals the number of characters.
C and C++ count bytes.
Trap one: in UTF-8 one Hangul syllable takes 3 bytes.
So if you use strlen or size() as it is, "안녕 hi" in example 1 is counted as 9 instead of 5 and the answer becomes 1.
In C and C++, count only the first byte of each character.
In UTF-8 every byte of a character after the first starts with the bits 10, so the number of bytes with (c & 0xC0) != 0x80 is the number of characters.
Trap two: C strlen and C++ size() return an unsigned integer (size_t).
If a C++ program counts the characters in a size_t and prints m - count, the result cannot go negative and wraps around to a huge number: example 2 prints 18446744073709551613 instead of -3.
Count in an int, or convert to int before subtracting.
Trap three: the message contains spaces, so you must read the whole line.
C++ cin >> msg stops at the first space and example 1 becomes 8 (use std::getline).
As an aside, the emoji 😀, which never appears in this problem, counts as 1 in Python and as 2 in JS, TS, Java, C# and Craykon, and takes 4 bytes in C and C++.

Pythonmain.py · 4 lines
m = int(input())msg = input()# len은 바이트가 아니라 글자(코드 포인트)를 센다: len("안녕") == 2print(m - len(msg))
JavaScriptmain.js · 5 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const m = Number(lines[0]);const msg = lines[1];// length는 UTF-16 단위의 수다. 한글 한 글자는 한 단위라 글자 수와 같다console.log(m - msg.length);
TypeScriptmain.ts · 6 lines
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const m: number = Number(lines[0]);const msg: string = lines[1];// length는 UTF-16 단위의 수다. 한글 한 글자는 한 단위라 글자 수와 같다console.log(m - msg.length);
JavaMain.java · 13 lines
import java.io.BufferedReader;import java.io.InputStreamReader;import java.nio.charset.StandardCharsets; public class Main {    public static void main(String[] args) throws Exception {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));        int m = Integer.parseInt(br.readLine().trim());        String msg = br.readLine();        // length()는 UTF-16 단위의 수다. 한글 한 글자는 한 단위라 글자 수와 같다        System.out.println(m - msg.length());    }}
C#Main.cs · 12 lines
using System; class Program{    static void Main()    {        int m = int.Parse(Console.ReadLine());        string msg = Console.ReadLine();        // Length는 UTF-16 단위의 수다. 한글 한 글자는 한 단위라 글자 수와 같다        Console.WriteLine(m - msg.Length);    }}
C++main.cpp · 18 lines
#include <iostream>#include <limits>#include <string> int main() {    int m;    std::cin >> m;    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');    std::string msg;    std::getline(std::cin, msg);    // size()는 바이트 수를 준다. UTF-8에서 글자의 첫 바이트만 세면 글자 수다    // (둘째 바이트부터는 모두 10xxxxxx 꼴이다)    int count = 0;   // size_t가 아니라 int: m - count가 음수가 될 수 있다    for (unsigned char c : msg) {        if ((c & 0xC0) != 0x80) count++;    }    std::cout << m - count << "\n";}
Cmain.c · 17 lines
#include <stdio.h>#include <stdlib.h> int main(void) {    char num[16], msg[700];   /* 한글 한 글자가 3바이트라 200글자면 600바이트까지 */    if (!fgets(num, sizeof num, stdin)) return 0;    if (!fgets(msg, sizeof msg, stdin)) return 0;    int m = atoi(num);    int count = 0;    /* strlen은 바이트 수를 준다. UTF-8에서 글자의 첫 바이트만 세면 글자 수다       (둘째 바이트부터는 모두 10xxxxxx 꼴이다) */    for (int i = 0; msg[i] != '\0' && msg[i] != '\n'; i++) {        if (((unsigned char)msg[i] & 0xC0) != 0x80) count++;    }    printf("%d\n", m - count);    return 0;}
Craykonmain.cray · 4 lines
m = Console.ReadLine().ToNumber();msg = Console.ReadLine();// 길이는 글자 수다: "안녕".길이 == 2Console.WriteLine(m - msg.Length);