0
1

Java String型の値の論理否定

Posted at

JavaにおけるString型の論理否定

String型は比較演算子を使う事が出来ない
その為一般にequalsメソッドで文字列が同じであるかを判定する

しかし同値であるかを判定するequalsメソッドは存在するが、論理否定は無いらしい

String型の論理否定を実装する場合以下のように書く

String 論理否定
public class Main {
    public static void main(String[] args) throws Exception {
        String str_1 = "ABC";
        String str_2 = "XYZ";
        
        if(!(str_1).equals(str_2)){
            System.out.print("hoge");
        }
    }
}
出力結果
hoge
A - Signboard.java
import java.util.*;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner scan = new Scanner(System.in);
        String[] str = {"C","O","D","E","F","E","S","T","I","V","A","L","2","0","1","6"};
        String[] S = scan.next().split("");
        int count = 0;
        
        for(int i = 0; i < str.length; i++){
            if(!(str[i]).equals(S[i])){
                count++;
            }
        }
        System.out.print(count);
    }
}

標準入力
C0DEFESTIVAL2O16
出力結果
2
0
1
0

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
0
1