{ }codelper
comparing stringsP0056

Compare two words in dictionary order

The first line gives the number of queries q.
Each of the next q lines gives two English words a and b separated by one space.
For each query print -1 if a comes before b, 0 if they are equal, and 1 if a comes after b.
Order is decided by character code (ASCII): compare from the first character, and at the first differing character the smaller code comes first.
Under this rule every uppercase letter (A–Z, 65–90) comes before every lowercase letter (a–z, 97–122), so "Zoo" comes before "apple".
If one word is the beginning of the other ("app" and "apple"), the shorter one comes first.

Input
1 ≤ q ≤ 1,000.
Words: uppercase and lowercase English letters, length 1 to 20
Output
q lines, each -1, 0 or 1
Example 1 · stdin
4
apple banana
app apple
Zoo apple
same same
stdout
-1
-1
-1
0
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

Comparing strings: Python, JS, TS, C++ and Craykon write a < b directly (all by character code).
Java a.compareTo(b), C strcmp(a, b), C++ a.compare(b) and C# string.Compare(a, b, StringComparison.Ordinal) return negative, 0 or positive, with no promise of -1 and 1. Java compareTo returns the code difference of the first differing characters ("a" vs "c" is -2) or the length difference, and C strcmp may also return a character difference depending on the implementation.
So keep only the sign with Integer.signum, Math.Sign or (r > 0) - (r < 0).
Python has no three-way compare function, so build it as (a > b) - (a < b).
Case trap: C# string.Compare(a, b) (without a StringComparison) uses culture rules, so "a" comes before "B", and JS a.localeCompare(b) does the same.
For character-code order use Ordinal in C# and < in JS.

Pythonmain.py · 4 lines
q = int(input())for _ in range(q):    a, b = input().split()    print((a > b) - (a < b))
JavaScriptmain.js · 7 lines
const [q, ...lines] = require("fs").readFileSync(0, "utf8").split("\n").map((x) => x.trim());const out = [];for (let i = 0; i < Number(q); i++) {  const [a, b] = lines[i].split(" ");  out.push(a < b ? -1 : a > b ? 1 : 0);}console.log(out.join("\n"));
TypeScriptmain.ts · 8 lines
import { readFileSync } from "node:fs";const [q, ...lines]: string[] = readFileSync(0, "utf8").split("\n").map((x) => x.trim());const out: number[] = [];for (let i = 0; i < Number(q); i++) {  const [a, b]: string[] = lines[i].split(" ");  out.push(a < b ? -1 : a > b ? 1 : 0);}console.log(out.join("\n"));
JavaMain.java · 16 lines
import java.io.BufferedReader;import java.io.InputStreamReader; public class Main {    public static void main(String[] args) throws Exception {        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        int q = Integer.parseInt(br.readLine().trim());        StringBuilder out = new StringBuilder();        for (int i = 0; i < q; i++) {            String[] p = br.readLine().trim().split(" ");            // compareTo는 -1/1이 아니라 "차이"를 돌려주므로 부호만 남긴다            out.append(Integer.signum(p[0].compareTo(p[1]))).append('\n');        }        System.out.print(out);    }}
C#Main.cs · 18 lines
using System;using System.Text; class Program{    static void Main()    {        int q = int.Parse(Console.ReadLine());        var out_ = new StringBuilder();        for (int i = 0; i < q; i++)        {            string[] p = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries);            // 글자 코드로 비교하려면 Ordinal(기본 string.Compare는 문화권 규칙을 따른다)            out_.Append(Math.Sign(string.Compare(p[0], p[1], StringComparison.Ordinal))).Append('\n');        }        Console.Write(out_);    }}
C++main.cpp · 13 lines
#include <iostream>#include <string> int main() {    std::ios::sync_with_stdio(false);    int q;    std::string a, b;    std::cin >> q;    for (int i = 0; i < q; i++) {        std::cin >> a >> b;        std::cout << (a < b ? -1 : a > b ? 1 : 0) << '\n';    }}
Cmain.c · 14 lines
#include <stdio.h>#include <string.h> int main(void) {    int q;    char a[32], b[32];    if (scanf("%d", &q) != 1) return 0;    for (int i = 0; i < q; i++) {        scanf("%31s %31s", a, b);        int r = strcmp(a, b);  /* 부호만 정해져 있다: 음수, 0, 양수 */        printf("%d\n", (r > 0) - (r < 0));    }    return 0;}
Craykonmain.cray · 19 lines
q = Console.ReadLine().ToNumber();for (i = 0; i < q; i++){    words = Console.ReadLine().Split();    a = words[0];    b = words[1];    if (a < b)    {        Console.WriteLine(-1);    }    else if (a > b)    {        Console.WriteLine(1);    }    else    {        Console.WriteLine(0);    }}