官术网_书友最值得收藏!

The replace() function

To confirm that we're all on the same page, let's employ one more method from the String class. If we head back to our documentation and scroll up, we can find the String's replace() method:

Unlike our toUpperCase() method, which took no arguments, replace() takes two characters as arguments. The function will return a new string where all the instances of the first character (oldChar) we give as an argument are replaced with the second character (newChar) we gave as an argument.

Let's utilize this function on our first println() line in StringsInJava.java. We'll type s3.replace() and give our function two characters as arguments. Let's replace the character g with the character o:

package stringsinjava; 
 
public class StringsInJava { 
    public static void main(String[] args) { 
       char c = 'c'; 
        String s1 = "stringone"; 
        String s2 = "stringtwo"; 
        String s3 = s1 + s2 + "LIT"; 
 
        s3 = s3.toUpperCase(); 
         
        System.out.println(s3.replace('g', 'o')); 
        System.out.println(s3); 
    } 
} 

If we run our program, of course, nothing happens. This is because by the time we reach the print statement, there are no lowercase g characters, and there are no lowercase g characters left in s3; there are only uppercase G characters. So let's try and replace the uppercase G characters:

System.out.println(s3.replace('G', 'o')); 
System.out.println(s3); 

Now if we run our program, we see the replacement happen on the first instance of println, not on the second instance. This is because we haven't actually changed the value of s3:

Excellent! You are now well-equipped, as long as you have the Java documentation handy, to call all sorts of String methods.

主站蜘蛛池模板: 双鸭山市| 漳平市| 永城市| 乐东| 安新县| 乌海市| 滨海县| 白水县| 山东省| 阿勒泰市| 南充市| 嫩江县| 杭锦旗| 安乡县| 饶河县| 文安县| 桃源县| 大石桥市| 阿坝| 神农架林区| 慈利县| 建宁县| 璧山县| 新和县| 泰兴市| 普兰店市| 庆云县| 郸城县| 黔江区| 麻栗坡县| 工布江达县| 乐亭县| 巨鹿县| 灵宝市| 韶关市| 宁津县| 永胜县| 阿拉尔市| 礼泉县| 麻栗坡县| 仁化县|