Posted in Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package LatihanString; /** * * @author Azhar */ public class StringEdit { public static void main(String[] args) { //mengubah karakter di dalam string String str1 = "abcde"; //mengambil 3 karakter pertama String str1x = str1.substring(0,3); System.out.println(str1x); //mengganti huruf d dengan huruf x String str1y = str1.substring(0, 3) + 'x' + str1.substring(4); System.out.println(str1y); } }Contoh 2: Menggunakan StringBuilder
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package LatihanString; /** * * @author Azhar */ public class StringEdit { public static void main(String[] args) { //mengubah karakter di dalam string String str1 = "abcde"; //menggunakan StringBuilder StringBuilder str1z = new StringBuilder(str1); str1z.setCharAt(3, 'x'); System.out.println(str1z); } }Contoh 3: Menggunakan charAt
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package LatihanString; /** * * @author Azhar */ public class StringEdit { public static void main(String[] args) { //mengubah karakter di dalam string String str1 = "abcde"; //mengubah string menjadi char[], ganti huruf, convert balik ke string char[] str1Char = str1.toCharArray(); str1Char[3] = 'x'; str1 = String.valueOf(str1Char); System.out.println(str1); } }Contoh 4: Menggunakan replace
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package LatihanString; /** * * @author Azhar */ public class StringEdit { public static void main(String[] args) { //mengubah karakter di dalam string String str1 = "abcde"; //menggunakan replace String str2x = str1.replace('d', 'x'); System.out.println(str2x); } }Contoh 5: Menggunakan char dan replace
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package LatihanString; /** * * @author Azhar */ public class StringEdit { public static void main(String[] args) { //mengubah karakter di dalam string //membuat method untuk mengubah karakter String test = "abcde"; String hasil = replace(test, 3, 'x'); System.out.println(hasil); } private static String replace(String str, int index, char replace) { char[] charx = str.toCharArray(); charx[index] = replace; return String.valueOf(charx); } }Selamat mencoba