Class String
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
is equivalent to:
Here are some more examples of how strings can be used:
The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. Case mapping is based on the Unicode Standard version specified by the Character class.
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For additional information on string concatenation and conversion, see The Java Language Specification.
Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.
A String represents a string in the UTF-16 format in which supplementary characters are represented by surrogate pairs (see the section Unicode Character Representations in the Character class for more information). Index values refer to char code units, so a supplementary character uses two positions in a String .
The String class provides methods for dealing with Unicode code points (i.e., characters), in addition to those for dealing with Unicode code units (i.e., char values).
Unless otherwise noted, methods for comparing Strings do not take locale into account. The Collator class provides methods for finer-grain, locale-sensitive String comparison.
How do I replace a character in a string in Java?
Using Java, I want to go through the lines of a text and replace all ampersand symbols ( & ) with the XML entity reference & .
I scan the lines of the text and then each word in the text with the Scanner class. Then I use the CharacterIterator to iterate over each characters of the word. However, how can I replace the character? First, Strings are immutable objects. Second, I want to replace a character ( & ) with several characters( amp&; ). How should I approach this?
11 Answers 11
Try using String.replace() or String.replaceAll() instead.
(Both replace all occurrences; replaceAll allows use of regex.)
The simple answer is:
Despite the name as compared to replaceAll, replace does do a replaceAll, it just doesn’t use a regular expression, which seems to be in order here (both from a performance and a good practice perspective — don’t use regular expressions by accident as they have special character requirements which you won’t be paying attention to).
Sean Bright’s answer is probably as good as is worth thinking about from a performance perspective absent some further target requirement on performance and performance testing, if you already know this code is a hot spot for performance, if that is where your question is coming from. It certainly doesn’t deserve the downvotes. Just use StringBuilder instead of StringBuffer unless you need the synchronization.
That being said, there is a somewhat deeper potential problem here. Escaping characters is a known problem which lots of libraries out there address. You may want to consider wrapping the data in a CDATA section in the XML, or you may prefer to use an XML library (including the one that comes with the JDK now) to actually generate the XML properly (so that it will handle the encoding).
Метод replace() в Java
Метод replace() заменяет указанный символ (или подстроку) в строке на новый.
Синтаксис метода:
Вызов:
Пример 1:
Если Вы запустите данный код на своем компьютере, в консоли Вы увидите следующее:
Комментарии к коду:
У нас есть переменная oldString, которая хранит строку «ABC». Представим, что нам надо заменить ‘A’ на ‘B’. Для этого мы используем метод replace(). Первым параметром мы указываем, что заменить (символ ‘A’), а вторым — чем заменить (символ ‘B’). Итого, получаем в консоли новую строку — «BBC».
- Обратите внимание — первая строка (oldString) не изменилась после применения метода. То-есть метод replace() возвращает новую строку.
Пример 2:
Если Вы запустите данный код на своем компьютере, в консоли Вы увидите следующее:
Комментарии к коду:
Как и в прошлом примере, мы заменили один символ на другой (в данном случае ‘a’ на ‘i’).
- Обратите внимание — метод replace() заменяет все символы в строке на новый, а не только его первое вхождение.
Пример 3:
Если Вы запустите данный код на своем компьютере, в консоли Вы увидите следующее:
Комментарии к коду:
Теперь мы заменяем не символы, а строки — а именно, мы ищем в строке «Java» подстроку «av» и заменяем на «oshu». Подстрока «av» встречается в строке «Java» один раз («J av a»). В результате выполнения метода, получаем новую строку «Joshua».
- Обратите внимание — подстроки не должны иметь одинаковую длину (длина строки «oshua» больше длины строки «av», но метод все равно работает корректно).
Данная статья написана Vertex Academy. Можно пройти наши курсы Java с нуля. Детальнее на сайте.
Replace string в Java
В работе программиста довольно часто некоторые задачи или их составляющие могут повторяться. Поэтому сегодня хотелось бы затронуть тему, которая часто встречается в повседневной работе любого Java-разработчика. Предположим, что вам из некоторого метода приходит некоторая строка. И всё в ней вроде бы хорошо, но есть какая-то мелочь, которая вас не устраивает. Например, не подходит разделитель, и вам нужен какой-то другой (или вовсе не нужен). Что можно сделать в такой ситуации? Естественно, воспользоваться методами replace класса String .