2つの文字列を比べる String.compare
ひとことで言うと
2 つの文字列の文字の順序にどのような違いがあるかを確認してください (ASCII エンコーディングで)。
ブロックとコード
文字列を比べる""と""
ブロックの文言は公式の日本語版に合わせています(形は簡易表示です)。
"".compare("")"".compare("")引数(ひきすう)
引数とは、ブロックの中で自分で選んだり入力したりする部分のことです。
| 名前 | 選べる値 | 意味 |
|---|---|---|
| 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 = TrueSee 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 = TrueSee 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