Java удалить все пробелы строки

How to remove duplicate white spaces in string using Java?

How to remove duplicate white spaces (including tabs, newlines, spaces, etc. ) in a string using Java?

9 Answers 9

yourString = yourString.replaceAll("\\s+", " "); 
System.out.println("lorem ipsum dolor \n sit.".replaceAll("\\s+", " ")); 

What does that \s+ mean?

\s+ is a regular expression. \s matches a space, tab, new line, carriage return, form feed or vertical tab, and + says «one or more of those». Thus the above code will collapse all «whitespace substrings» longer than one character, with a single space character.

@SuhrobSamiev — String.replaceAll() has been in Java since JDK 1.4. docs.oracle.com/javase/1.4.2/docs/api/java/lang/…, java.lang.String)

The string literal «\\» represents the string consisting of a single backslash. So to represent \s+ you write «\\s+» .

If the input is «foo\t\tbar » you’ll get «foo\tbar » as output
But if the input is «foo\t bar» it will remain unchanged because it does not have any consecutive whitespace characters.

If you treat all the whitespace characters(space, vertical tab, horizontal tab, carriage return, form feed, new line) as space then you can use the following regex to replace any number of consecutive white space with a single space:

But if you want to replace two consecutive white space with a single space you should do:

String str = " Text with multiple spaces "; str = org.apache.commons.lang3.StringUtils.normalizeSpace(str); // str = "Text with multiple spaces" 

Try this — You have to import java.util.regex.*;

 Pattern pattern = Pattern.compile("\\s+"); Matcher matcher = pattern.matcher(string); boolean check = matcher.find(); String str = matcher.replaceAll(" "); 

Where string is your string on which you need to remove duplicate white spaces

hi the fastest (but not prettiest way) i found is

while (cleantext.indexOf(" ") != -1) cleantext = StringUtils.replace(cleantext, " ", " "); 

this is running pretty fast on android in opposite to an regex

Читайте также:  Php date to month name

i know, you have to add more of these while loops for other entities. But this code run much faster on android as these regex, i had to process complete ebooks.

Enormously faster on desktop too. Haven’t tested it for a big string, but if you plan on running it on a lot of small strings this is the answer you are looking for.

Though it is too late, I have found a better solution (that works for me) that will replace all consecutive same type white spaces with one white space of its type. That is:

Notice there are still leading and trailing white spaces. So my complete solution is:

str = str.trim().replaceAll("(\\s)+", "$1")); 

Here, trim() replaces all leading and trailing white space strings with «». (\\s) is for capturing \\s (that is white spaces such as ‘ ‘, ‘\n’, ‘\t’) in group #1. + sign is for matching 1 or more preceding token. So (\\s)+ can be consecutive characters (1 or more) among any single white space characters (‘ ‘, ‘\n’ or ‘\t’). $1 is for replacing the matching strings with the group #1 string (which only contains 1 white space character) of the matching type (that is the single white space character which has matched). The above solution will change like this:

I have not found my above solution here so I have posted it.

Источник

Удалить все пробелы, табуляцию, символы и т.д. из String Java?

Я считываю текст в строку. хочу удалить абсолютно все кроме букв. Пробелы, переходы на новую строку, Абзацы, символы, ну и т.д для последующего подсчета биграмм. Пытаюсь сделать это регулярным выражением. У меня ничего не выходит

FileInputStream inFile = new FileInputStream("c:\\bukovski.txt"); byte[] str = new byte [inFile.available()]; inFile.read(str); String text = new String(str); //String textWithoutspaces = new String(); //text = FilterText.filterWithSpaces(text); String textWithoutSpaces = text.toLowerCase().replaceAll("//s+", ""); System.out.println(textWithoutSpaces);

Для начала, такое выраение не убирает переходы на новую строку в некоторых случаях

Читайте также:  Ajax php error codes

replaceAll(«[^а-я]+», «»);
Возвращает ничего

EugeneP2

import java.io.*; public class CharCleaner < public static void main(String[] args) throws IOException < try ( Reader reader = new BufferedReader(new FileReader(new File("sourceFile.txt"))); Writer writer = new BufferedWriter(new FileWriter(new File("resultFile.txt"))) ) < int ch; while ((ch = reader.read()) != -1) < if (Character.isAlphabetic(ch)) < writer.write(ch); >> writer.flush(); > catch (IOException e) < e.printStackTrace(); >> >


Не грузит весь фал в память, при чтении и записи файла есть буферизация, в процессе работы не создает кучу String объектов методами replace*

Therapyx

Вот недавно писал для замены строк в текст фаиле с 001, 002, 003, 004. 500 хД чуток переделал, там где стринги таб, и ньюлайн, просто добавь еще твои варианты и вставь в лупе доп строку для этого стринга. Т.е. просто сделай все нужные варианты, которые нужны именно тебе. В данном же примере я сделал только пробелы и переходы на новую строку

import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class Replace < public static void main(String[] args) throws IOException< LineNumberReader lnr = new LineNumberReader(new FileReader(new File("C:/test.txt"))); lnr.skip(Long.MAX_VALUE); System.out.println(lnr.getLineNumber() + 1 + " summary rows"); lnr.close(); Path path = Paths.get("C:/test.txt"); Charset charset = StandardCharsets.UTF_8; String content = new String(Files.readAllBytes(path), charset); String tab = " "; String newLine = "\n"; for (int i = 0; i < lnr.getLineNumber() + 2; i++) < content = content.replaceAll(tab, ""); content = content.replaceAll(newLine, ""); Files.write(path, content.getBytes(charset)); >> >

Источник

Как убрать пробелы в строке java

А если Вам необходимо убрать пробелы в начале и в конце, есть метод trim() который удаляет пробелы в начале и конце строки:

piblic static void main(String[] args)  String str = " Java- top "; System.out.println(str); System.out.println(str.trim()); > // Выход: // Java- top // Java- top // результат работы trim() 

Источник

Как удалить ВСЕ пробелы из String?

Удалить все пробелы и табуляции но не перенос на другую строку из текста в переменной string
Здравствуйте. Скажите как удалить в тексте все пробелы и табуляции но не специальные символы те.

Как удалить все пробелы в строке, и если есть кавычки, то между ними пробелы заменить на %
Как удалить все пробелы в строке, и если есть кавычки, то между ними пробелы заменить на %? Вот.

Во введенном тексте удалить все пробелы, если пробелы присутствуют
Создать программу, которая спрашивает имя пользователя и здоровается с ним. Затем, предлагается.

Удалить все латинские буквы в строке, удалить все пробелы, вывести сумму чисел
Удалить все латинские буквы в строке, удалить все пробелы, вывести сумму чисел. Прошу помочь я не.

Ну да, я не нашёл там метода removeAll, можно ещё toCharArray сделать. А на что заменяла то, на звёздочки? Хотя даже с toCharArray без StringBuilder-a не обойтись)

ЦитатаСообщение от RequiemMass Посмотреть сообщение

String a = "a b c d e"; String b = a.replaceAll(" ", "");

Удалить в строке все лишние пробелы, то есть серии подряд идущих пробелов заменить на одиночные пробелы
Я уже решал эту задачу с помощью циклов и символьных массивов, и выкладывал на этот форум , но я не.

Как удалить все пробелы из текста
Как удалить все пробелы из текста ? а то у меня не работает: string str =.

Как удалить все числа и пробелы в строке?
Пробелы удаляются, а из цифр удаляется только часть. string line; getline(text, line);.

Как удалить все пробелы в каждой строке файла?
Как удалить все пробелы в каждой строке файла на c# ? string stroka = null; string.

Удалить пробелы из элементов массива string
Есть массив string c = new string; Его элементы записаны так: строка1 _строка2 _строка3.

Удалить подряд идущие пробелы, не используя библиотеку string
Удалить подряд идущие пробелы не используя библиотеку string.h Пример реализации: #include.

Источник

Оцените статью