JAvaにおける文字列Stringの基本操作


  • 文字列定義
    //      
            // ①         
            String s1 = new String();
            System.out.println(s1); //     
    
            // ②      ,       
            char[] arrayList = {'a', 'b', 'c'};
            String s2 = new String(arrayList);
            System.out.println(s2); //    abc
    
            // ③      ,        
            byte[] byteList = {97, 98, 99};
            String s3 = new String(byteList);
            System.out.println(s3); //    abc
    
            // ④    
            String str = "Welcome to China!";
            String str2 = "welcome to China!";
    
  • 文字列の比較
    //        == (               )
            System.out.println(str == "Welcome to China!"); // true
            
    //         equals()
            System.out.println(str.equals(str2)); // false
    
    //        (      ) equalsIgnoreCase()
            System.out.println(str.equalsIgnoreCase(str2)); // true
    
  • 文字列長取得
    //         length()
            System.out.println(str.length()); // 17
    
  • 文字列接合
    //       concat    +
            System.out.println(str.concat(str2)); // Welcome to China!welcome to China!
            System.out.println(str + str2); // Welcome to China!welcome to China!
    
  • 文字列指定位置の内容
     //            charAt()
            System.out.println(str.charAt(0)); // W
    
  • 文字列の中のある文字が初めて現れる位置
     //                 indexOf()
            System.out.println(str.indexOf("lco")); // 2
    
  • 文字列切り取り
    //       substring()
            System.out.println(str.substring(8)); // to China!
            System.out.println(str.substring(0, 8)); //      Welcome
    
  • 文字列カット
    //       split()
            String[] newList = str.split(" "); //         
            System.out.println(Arrays.toString(newList)); // [Welcome, to, China!]
    
  • 文字列変換
    //      
            // ①        
            char[] arrayList1 = str.toCharArray();
            System.out.println(arrayList1); // Welcome to China!
            // ②        
            byte[] byteList1 = str.getBytes();
            System.out.println(Arrays.toString(byteList1));
            //      :[87, 101, 108, 99, 111, 109, 101, 32, 116, 111, 32, 67, 104, 105, 110, 97, 33]
    
  • 文字列置換
    //      
            String newStr = str.replace("!", "?");
            System.out.println(newStr); // Welcome to China?