Java用代码演示String类中的以下方法的用法
用代码演示String类中的以下方法的用法
(1)boolean isEmpty(): 判断字符串是不是空串,如果是空的就返回true
(2)char charAt(int index): 返回索引上的字符
(3)String toLowerCase(): 字符串转成小写
(4)String toUpperCase(): 字符串转成大写
(5)String repalce(char oldChar, char newChar): 将字符串中的老字符,替换为新字符
(6)String repalce(String old, String newstr): 将字符串中的老字符串,替换为新字符串
(7)String trim(): 去掉字符串两端空格
代码如下:
1 package com.aaa.zuoye; 2 3 public class ZuoYe { 4 public static void main(String[] args) { 5 fun7(); 6 } 7 // (7)String trim(): 去掉字符串两端空格 8 public static void fun7(){ 9 String str=" helloword "; 10 str=str.trim(); 11 System.out.println(str); 12 } 13 // (6)String repalce(String old, String newstr): 将字符串中的老字符串,替换为新字符串 14 public static void fun6(){ 15 String str="hellohaini"; 16 str=str.replaceFirst("h", "1"); 17 System.out.println(str); 18 } 19 // (5)String repalce(char oldChar, char newChar): 将字符串中的老字符,替换为新字符 20 public static void fun5(){ 21 String str="hello"; 22 str=str.replace("o", "a"); 23 System.out.println(str); 24 } 25 // (4)String toUpperCase(): 字符串转成大写 26 public static void fun4(){ 27 String str="hellO"; 28 System.out.println(str.toUpperCase()); 29 } 30 // (3)String toLowerCase(): 字符串转成小写 31 public static void fun3(){ 32 String str1="helloWord"; 33 System.out.println(str1.toLowerCase()); 34 } 35 // (2)char charAt(int index): 返回索引上的字符 36 public static void fun2(){ 37 String str1="helloWord"; 38 System.out.println(str1.charAt(2)); 39 } 40 //(1)boolean isEmpty(): 判断字符串是不是空串,如果是空的就返回true 41 public static boolean fun1(){ 42 String str1=""; 43 if(str1.isEmpty()==true){ 44 return true; 45 } 46 return false; 47 } 48 }