2つの文字列を比べる String.compare

テキスト公式データ取得日:2026年11月13日動作確認待ち

ひとことで言うと

2 つの文字列の文字の順序にどのような違いがあるかを確認してください (ASCII エンコーディングで)。

ブロックとコード

ブロックの文言は公式の日本語版に合わせています(形は簡易表示です)。

引数(ひきすう)

引数とは、ブロックの中で自分で選んだり入力したりする部分のことです。

名前選べる値意味
that文字列ターゲット文字列と比較する文字列

使用例

The string "abcdefg" is greater than "abcdefa". They are almost the same but the last letter of the second string is less than the last letter of the first one. This makes the whole second string compare as less. In blocks, the comparison of these strings looks like:

JavaScript

let iamGreater = false;
if ("abcdefg".compare("abcdefa") > 0) {
    iamGreater = true;
}

Python

iamGreater = False
if "abcdefg".compare("abcdefa") > 0:
    iamGreater = True

See which bird is the same as a "duck".

JavaScript

let match = false;
let bird = "duck";
if (bird.compare("crow") == 0) {
    match = true;
} else if (bird.compare("goose") == 0) {
    match = true;
} else if (bird.compare("duck") == 0) {
    match = true;
}

Python

match = False
bird = "duck"
if bird.compare("crow") == 0:
    match = True
elif bird.compare("goose") == 0:
    match = True
elif bird.compare("duck") == 0:
    match = True

See how other birds compare to a "duck".

JavaScript

let birds = ["crow", "DUCK", "goose", "Duck", "eagle", "osprey"];
let lesserBirds = 0;
let greaterBirds = 0;
let ducks = 0;

for (let bird of birds) {
    let result = bird.compare("duck");
    if (result < 0) {
        lesserBirds++;
    } else if (result > 0) {
        greaterBirds++;
    } else {
        ducks++;
    }
}

Python

birds = ["crow", "DUCK", "goose", "Duck", "eagle", "osprey"]
lesserBirds = 0
greaterBirds = 0
ducks = 0
for bird in birds:
    result = bird.compare("duck")
    if result < 0:
        lesserBirds += 1
    elif result > 0:
        greaterBirds += 1
    else:
        ducks += 1
執筆:鈴木孝昌官公庁のWeb・システム開発を担当する現役プロジェクトマネージャー。マイクラカップ沖縄代表チームを指導(第6回・第7回、第7回TBS賞)。
沖縄マイクラ部で、子どもたちにMakeCodeを教えています。プロフィールと編集方針
Instagramで教室の様子を見る
noteで記事を読む