Java字符串类型的各式各样方法

    技术2022-07-10  174

    相信大家在刚学习java时很快就接触到字符串输出,以下有几个字符串输出方法可供大家参考:

    1.比较字符串大小:

    public class Main { public static void main(String[] args) { int com; String str1 = "China"; String str2 = "CHINA"; com = str1.compareTo(str2); //按字典方式比较两个字符串。 System.out.println(com); com = str1.compareToIgnoreCase(str2); //按字典比较两个字符串,忽略大小写差异。 System.out.println(com); } }

    输出结果:

    32 0

    2.连接字符串

    public class Main { public static void main(String[] args) { String str1 = "China"; String str2 = "CHINA"; String str3; System.out.println(str1.concat(str2)); //以变量形式连接字符串 System.out.println(str1.concat(" i love you!")); //使用方法连接 System.out.println(str1 + " i love you!"); //直接加号连接,非常方便 } }

    输出结果:

    ChinaCHINA China i love you! China i love you!

    3.字符串返回指定索引处的 char 值

    public class Main { public static void main(String[] args) { String str_1 = "china"; char chars = str_1.charAt(3); System.out.println("chars = " + chars); } }

    输出结果:

    chars = n

    4.用码数或者字符串的形式搜索字符串位置

    public class Main { public static void main(String[] args) { String str1 = "China"; // 用码点查找字符串 int num1 = str1.indexOf(1); System.out.println("num = " + num1); // 以字符串查找字符串 int num2 = str1.indexOf("ina"); System.out.println("num2 = " + num2); // 以字符串查找字符串,以fromindex作为开始 int num3 = str1.indexOf("C", 0); System.out.println("num3 = " + num3); } }

    num1 = -1 num2 = 2 num3 = 0

    5.其他

    public class Main { public static void main(String[] args) { String str1 = " China "; int num1 = str1.length(); System.out.println("num1 = " + num1); // 找到旧字符串的目标,使用新的将其取代 String str2 = str1.replace("hina","HINA"); System.out.println("str2 = " + str2); // substring(子串)返回字符串中选中的字符串 String str3 = str2.substring(0,5); System.out.println("str3 = " + str3); // 改变字符串大小写 String str4 = str1.toLowerCase(); System.out.println("str4 = " + str4); String str5 = str1.toUpperCase(); System.out.println("str5 = " + str5); // 玄学方法 String str6 = str1.trim(); System.out.println("str6 = " + str6); String str7 = str1.join(" is"," my"," home",", i love it"); System.out.println("str7 = " + str7); } }

    num1 = 7 str2 = CHINA str3 = CHIN str4 = china str5 = CHINA str6 = China str7 = my is home is, i love it

    Processed: 0.019, SQL: 9