English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
يستخدم Java String replace() باستخدام الرمز/النص الجديد استبدال كل رمز/نص معين في السلسلة
نظام replace()
string.replace(char oldChar, char newChar)
أو
string.replace(CharSequence oldText, CharSequence newText)
لإجراء استبدال رمز واحد، يستخدم طريقة replace() إثنين من المعلمات التالية:
oldChar - الرمز الذي يتم استبداله في السلسلة
newChar - يتم استبدال الرمز المحدد بالرمز
لإجراء استبدال النص، يستخدم طريقة replace() إثنين من المعلمات التالية:
oldText - النص الذي يتم استبداله في السلسلة
newText - يتم استبدال النص المعين بالسلسلة
يتم استبدال كل ظهور للرمز أو النص المحدد في السلسلة بمثيل جديد.
class Main { public static void main(String[] args) { String str1 = "abc cba"; //جميع الـ “a” موجودة في السلسلة تم استبدالها بالـ “z” System.out.println(str1.replace('a', 'z')); // zbc cbz //جميع الـ “L” موجودة في السلسلة تم استبدالها بالـ “J” System.out.println("Lava".replace('L', 'J')); // Java //الرمز غير موجود في السلسلة System.out.println("Hello".replace('4', 'J')); // Hello } }
Note:إذا لم يكن الرمز المطلوب استبداله موجودًا في السلسلة، فإن replace() يعود إلى السلسلة الأصلية.
class Main { public static void main(String[] args) { String str1 = "C++ Programming"; //所有出现的“c++”都被替换为“Java” System.out.println(str1.replace("C++", "Java")); // Java Programming // All occurrences of “a” are replaced with “zz” System.out.println("aa bb aa zz".replace("aa", "zz")); // zz bb aa zz // The substring is not in the string System.out.println("Java".replace("C++", "C")); // Java } }
Note:If the substring to be replaced is not in the string, then replace() returns the original string.
It should be noted that the replace() method replaces the substring from start to end. For example,
"zzz".replace("zz", "x") // xz
The output of the above code is xz, not zx. This is because the replace() method replaces the first zz with x
If you need to replace a substring based on a regular expression, please useJava String replaceAll() method.