Java удалить символы до точки

Java: удалить все символы после точки

Второй аргумент split ( 2 ) указывает, что мы должны разбивать только на первое вхождение . ; это быстрее, чем расщепление на все случаи . что случилось бы, если бы мы не предоставили этот второй аргумент.

Соответствующая документация

Просто используйте следующее:

String mainChapterNum = chapterNumber.substring(0, chapterNumber.indexOf(".")); 

Это вернет подстроку вашего текущего номера главы, начиная с первого символа, который помещен в индекс номер 0 и заканчивается до первого появления «.»

String chapterNumber = "1.2.1"; int index = chapterNumber.indexOf("."); String mainChapterNumber = chapterNumber.substring(0,index); 

Есть несколько способов сделать это. Самый простой, который я бы порекомендовал, это использовать подстроку и indexOf: Вот так:

String result = chapterNumber.substring(0, chapterNumber.indexOf(".")); 

Другой способ сделать это будет так:

String result = chapterNumber.split("\\.")[0]; 
String mainChapterNumber = chapterNumber.substring(0,chapterNumber.indexOf(".")); 

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

Попробуйте поиграть с индексами вашей строки. Найдите индекс первой точки и затем используйте substring метод, чтобы сохранить подстроку между источником и этим вхождением.

Источник

Работа строками, удалить и заменить до определенного символа

Дано строка. До первой точки удалить все запятые. После первой точки все символы-«5», заменить на «+»-символы. Помогите пожалуйста.

Удалить часть строки от определенного символа до определенного символа
Всем привет, есть строка 127.0.0.1(spec) (domen\admin — user) как удалить не нужные символы.

Как скопировать подстроку из строки до определенного символа? Или удалить, начиная с этого символа
Добрый вечер. Ответ искал, но не нашёл. Предположим, есть строка: ABC|DEF Надо скопировать.

Удалить после определенного символа
Есть IP в в виде строки, например 192.168.168.168, может быть 192.168.16.16 и т.д. Может быть любое.

Удалить подстроку до определенного символа
Из строки нужно удалить подстроку до #. Например (длина строки или подстроки может быть разной).

Почитайте, например: http://study-java.ru/uroki-jav. sa-string/
В общих чертах, вам приблизительно надо следующее:
Найти индекс точки через, допустим, indexOf(‘.’). Заменить в строке до этого индекса все «,», например. методом replaceAll
То же самое проделать и для второго куска строки.

Эксперт Java

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
public class Main { public static void main(String[] args) { String str = "фы,в,а прdfverrо,лд,жэ. йцук5ен гш5щз5rfrf55rf5ъ: яч5сми5ть5бю"; String Str1 = str.substring(+ 0, str.indexOf('.')); String A = Str1.replaceAll(",", ""); String Str2 = str.substring(str.indexOf('.')); String B = Str2.replace ('5', '+'); String result = A + B; System.out.print(result); // write your code here } }

Удалить дубликаты определённого символа
Существует строка, например ////aa/bbb//c/// На выходе нужно получить: /aa/bbb/c/ То есть.

Читайте также:  До какого размера вырастает королевский питон

Заменить часть String с определенного символа до другого
Как заменить часть string с определенного символа до другого? Т.е у меня такой набор символов.

Как удалить текст до определенного символа
Доброго времени суток, друзья Подскажите как возможно решить такие задачи через VBA: Есть.

Удалить текст после определенного символа
Здравствуйте! Есть текст: "111; 222; 333; 444; 555; 666; 777" Нужно сделать так, что бы при.

Источник

How To Remove a Character from a String in Java

How To Remove a Character from a String in Java

In this article, you’ll learn a few different ways to remove a character from a String object in Java. Although the String class doesn’t have a remove() method, you can use variations of the replace() method and the substring() method to remove characters from strings.

Note: String objects are immutable, which means that they can’t be changed after they’re created. All of the String class methods described in this article return a new String object and do not change the original object. The type of string you use depends on the requirements of your program. Learn more about other types of string classes and why strings are immutable in Java.

The String class has the following methods that you can use to replace or remove characters:

  • replace(char oldChar, char newChar) : Returns a new String object that replaces all of the occurrences of oldChar in the given string with newChar . You can also use the replace() method, in the format replace(CharSequence target, CharSequence replacement) , to return a new String object that replaces a substring in the given string.
  • replaceFirst(String regex, String replacement) : Returns a new String object that replaces the first substring that matches the regular expression in the given string with the replacement.
  • replaceAll(String regex, String replacement) : Returns a new String object that replaces each substring that matches the regular expression in the given string with the replacement.
  • substring(int start, int end) : Returns a new String object that contains a subsequence of characters currently contained in this sequence. The substring begins at the specified start and extends to the character at index end minus 1.

Notice that the first argument for the replaceAll() and replaceFirst() methods is a regular expression. You can use a regular expression to remove a pattern from a string.

Note: You need to use double quotes to indicate literal string values when you use the replace() methods. If you use single quotes, then the JRE assumes you’re indicating a character constant and you’ll get an error when you compile the program.

Читайте также:  Php array column to key

Remove a Character from a String in Java

You can remove all instances of a character from a string in Java by using the replace() method to replace the character with an empty string. The following example code removes all of the occurrences of lowercase “ a ” from the given string:

String str = "abc ABC 123 abc"; String strNew = str.replace("a", ""); 

Remove Spaces from a String in Java

You can remove spaces from a string in Java by using the replace() method to replace the spaces with an empty string. The following example code removes all of the spaces from the given string:

String str = "abc ABC 123 abc"; String strNew = str.replace(" ", ""); 

Remove a Substring from a String in Java

You can remove only the first occurrence of a character or substring from a string in Java by using the replaceFirst() method to replace the character or substring with an empty string. The following example code removes the first occurrence of “ ab ” from the given string:

String str = "abc ABC 123 abc"; String strNew = str.replaceFirst("ab", ""); 

Remove all the Lowercase Letters from a String in Java

You can use a regular expression to remove characters that match a given pattern from a string in Java by using the replace.All() method to replace the characters with an empty string. The following example code removes all of the lowercase letters from the given string:

String str = "abc ABC 123 abc"; String strNew = str.replaceAll("([a-z])", ""); 

Remove the Last Character from a String in Java

There is no specific method to replace or remove the last character from a string, but you can use the String substring() method to truncate the string. The following example code removes the last character from the given string:

String str = "abc ABC 123 abc"; String strNew = str.substring(0, str.length()-1); 

Try it out

The following example file defines a class that includes all of the method examples provided in this article, and prints out the results after invoking each method on the given string. You can use this example code to try it out yourself on different strings using different matching patterns and replacement values.

If you have Java installed, you can create a new file called JavaStringRemove.java and add the following code to the file:

 public class JavaStringRemove  public static void main(String[] args)  String str = "abc ABC 123 abc"; // Remove a character from a string in Java System.out.println("String after removing all the 'a's = "+str.replace("a", "")); // Remove spaces from a string in Java System.out.println("String after removing all the spaces = "+str.replace(" ", "")); // Remove a substring from a string in Java System.out.println("String after removing the first 'ab' substring = "+str.replaceFirst("ab", "")); // Remove all the lowercase letters from a string in Java System.out.println("String after removing all the lowercase letters = "+str.replaceAll("([a-z])", "")); // Remove the last character from a string in Java System.out.println("String after removing the last character = "+str.substring(0, str.length()-1)); > > 

Compile and run the program:

You get the following output:

Output
String after removing all the 'a's = bc ABC 123 bc String after removing all the spaces = abcABC123abc String after removing the first 'ab' substring = c ABC 123 abc String after removing all the lowercase letters = ABC 123 String after removing the last character = abc ABC 123 ab

Each method in the JavaStringRemove example class operates on the given string. The output shows that the characters specified in each method have been removed from the string.

Conclusion

In this article you learned various ways to remove characters from strings in Java using methods from the String class, including replace() , replaceAll() , replaceFirst() , and substring() . Continue your learning with more Java tutorials.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Java: удалить все символы после точки

второй аргумент split ( 2 ) указывает, что мы должны разделить только на первый возникновения . ; это быстрее, чем разбиение на все экземпляры . что и произошло бы, если бы мы не предоставили этот второй аргумент.

соответствующие Документация

просто используйте следующую конструкцию:

String mainChapterNum = chapterNumber.substring(0, chapterNumber.indexOf(".")); 

это вернет подстроку вашего текущего номера главы, начиная с первого символа, который помещается в индекс 0 и заканчивается до первого появления «.»

String chapterNumber = "1.2.1"; int index = chapterNumber.indexOf("."); String mainChapterNumber = chapterNumber.substring(0,index); 

попробуйте сыграть с индексами вашей строки. Найти индекс первой точки, а затем использовать substring метод сохранения подстроки между началом и этим событием.

есть несколько способов сделать это. Самый простой-я бы порекомендовал использует подстроку, и indexOf: Вот так:

String result = chapterNumber.substring(0, chapterNumber.indexOf(".")); 

другой способ сделать это было бы так:

String result = chapterNumber.split("\.")[0]; 

попробовать, как показано ниже.

String chapterNumber = "1.2.1"; String[] getdt = chapterNumber.split("\."); String mainChapterNumber = getdt[0]; 

просто для записи, другое решение с использованием разделитель гуавы:

String mainChapterNumber = Iterables.get(Splitter.on('.').split(chapterNumber), 0); 

это имеет то преимущество, что не использует механизм регулярных выражений (который не является легким, не используйте принятое решение в цикле).

String mainChapterNumber = chapterNumber.substring(0,chapterNumber.indexOf(".")); 

Источник

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