LoginSignup
4
1

More than 5 years have passed since last update.

String.Compareが覚えられない

Last updated at Posted at 2015-03-27

初歩的過ぎて笑う事案だけど、ここ1年で2,30回ぐらい悩んだレベルのクズっぷりなのでこの際メモ。

String.Compare(strA, strB)とstrA.CompareTo(strB)は同じだけど、私がよく使うのが後者なので、以降strA.CompareTo(strB)を使用。


intで1,0,-1の何れかが帰ってくる。

昇順でstrA,strBと並ぶときはstrA.CompareTo(strB)は-1
昇順でstrB,strAと並ぶときはstrA.CompareTo(strB)は1

昇順でnull,string.Emptyと並ぶ。

0の返り値を期待する場合はCompareでなくEqualsを使う。


strAがstrBより大/小と考えるよう覚えるか、strBがstrAより大/小と考えるよう覚えるか、どっちがいいんだろうな。

人によって違うんだろうけど、strA.CompareTo(strB)を使ってると、「strBがstrAより大/小」の方がなんとなくシックリくる感じはある。ってメモしてるうちに気づいたのは、「strBがstrAより大/小」だと、大⇒-1、小⇒1だから混乱してたのかなってことと、前者は昇順の考え方で後者は降順の考え方だということ。

降順でstrA,strBと並ぶときはstrA.CompareTo(strB)は1
降順でstrB,strAと並ぶときはstrA.CompareTo(strB)は-1

うーん、むずかしい。

-(strA.CompareTo(strB))とでも書いてやろうか!w


4年経った今(2019/04/10)

割と覚えている(気がする)

A.CompareTo(B)も似たようなものだと思います。
A compare to B
A(主語)をBと比較する
すなわち、Bと比較してAがどうか

このコメントに救われています。
ありがとうございます。

4
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1