I need to remove character from string.
the String like
String a="{aaaaa{bbbbbb}aaaa}";
How to remove {bbbbbb} from this string.
this is example string only i need to remove the string between {——}.not possible to replace
asked Jun 11, 2014 at 6:51
SreekanthSreekanth
4073 gold badges8 silver badges20 bronze badges
3
removes all
while (a.contains("{bbbbbb}")){
a = a.replaceAll("{bbbbbb}", "");
}
answered Mar 11, 2021 at 12:57
1
we can do like this
String a="{aaaaa{bbbbbb}aaaa}";
String target=a.copyValueOf("{bbbbbb}".toCharArray());
a=a.replace(target, "");
output will be {aaaaaaaaa}
answered Jun 11, 2014 at 7:00
iKingiKing
66710 silver badges14 bronze badges
4
String str = "{aaaaa{bbbbbb}aaaa}";
String toRemove = "{bbbbbb}";
int x = str.indexOf(toRemove);
str = str.substring(0,x) + str.substring(x+toRemove.length(),str.length());
System.out.println(str);
answered Jun 11, 2014 at 7:03
4
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
Given a string and a word that task to remove the word from the string if it exists otherwise return -1 as an output. For more clarity go through the illustration given below as follows.
Illustration:
Input : This is the Geeks For Geeks word="the" Output : This is Geeks For Geeks Input : Hello world Hello" word = Hello Output : world Explanation: The given string contains the word two times Input : Hello world word = GFG Output : Hello world Explanation: word doesn't exists in the string
Now in order to reach the goal, we will be discussing ou two approaches namely as follows:
- Naive approach using searching techniques
- Optimal approach using String.replaceAll() Method
Method 1: Using searching techniques
- Convert the string into a string array.
- Iterate the array and check the word not equal to the given word.
- Concatenate the word into a new string array name as a new string.
- Print the new string.
Example
Java
import
java.io.*;
class
GFG {
static
void
remove(String str, String word)
{
String msg[] = str.split(
" "
);
String new_str =
""
;
for
(String words : msg) {
if
(!words.equals(word)) {
new_str += words +
" "
;
}
}
System.out.print(new_str);
}
public
static
void
main(String[] args)
{
String str =
"This is the Geeks For Geeks"
;
String word =
"the"
;
remove(str, word);
}
}
Output
This is Geeks For Geeks
Time Complexity: O(n), where n is the length of the given string.
Auxiliary Space: O(n), where n is the length of the given string
Method 2: Using String.replaceAll() Method
- This method takes two input old_word and the new word in the regex format.
- Replace all the old_word with the new word.
- Returns the resultant string.
Example
Java
import
java.io.*;
class
GFG {
public
static
void
main(String[] args)
{
String str =
"This is the Geeks For Geeks"
;
String word =
"the"
;
str = str.replaceAll(
"the"
,
""
);
str = str.trim();
System.out.print(str);
}
}
Output
This is Geeks For Geeks
Time Complexity: O(n)
Auxiliary Space: O(n)
Like Article
Save Article
Remove word from string java: Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language
- Java program to delete a word from sentence using replaceAll() method.
In this java program, we have to remove a word from a string using replaceAll method of String class. Deleting a word from a sentence is a two step process, first you have to search the word the given sentence. Then you have to delete all characters of word from string and shift the characters to fill the gap in sentence.
For Example,
Input Sentence : I love Java Programming
Word to Delete : Java
Output Sentence : I love Programming
Java program to delete a word from a sentence
In this program, we will use replaceAll() method of String class, which replaces the each occurrence of given word in sentence with “”. Hence deleting the word from sentence.
package com.tcc.java.programs; import java.util.Scanner; /** * Java Program to Delete Vowels from String */ public class DeleteWordFromSentence { public static void main(String args[]) { String sentence, word; Scanner scanner = new Scanner(System.in); System.out.println("Enter a Sentence"); sentence = scanner.nextLine(); System.out.println("Enter word you want to delete from Sentence"); word = scanner.nextLine(); // Deleting word from sentence = sentence.replaceAll(word, ""); System.out.println("Output Sentencen" + sentence); } }
Output
I love Java Programming Enter word you want to delete from Sentence Java Output Sentence I love Programming
Java provides several methods for removing substrings from Strings.
1) Using replace method
This method belongs to the Java String class and is overloaded to provide two different implementations of the same method.
In the first approach, a new character is added to a string to replace every previous character.
This way returns the string with the new characters after all the old characters have been updated.
Syntax:
The procedure returns this string if the new character cannot be located in the string.
Example:
Output:
2) Using Charsequence
The second technique substitutes the desired string of characters for the CharSequence, which is just a collection of characters.
Syntax:
This operation and the first merely differ in that it substitutes a string of characters.
Example:
Output:
3) Replace the Substring with an empty string
Java allows you to easily replace a substring you want to delete from the String with an empty String.
Syntax:
Example:
Output:
4) Using String’s replaceFirst method
This method searches for a string that matches a regular expression and, if one is found, replaces it with the given string.
Behind the scenes, this function extracts the text using a regular expression by using the compile() and matcher() methods of the Pattern class.
Syntax:
A regular expression will be created to extract a number from a string and replace it with another number as a string.
Note: Only the first two digits of the string will be changed by this number; the remaining digits will remain unchanged.
Example:
Output:
5) replaceFirst() method
The replaceFirst() method can be used with an empty String to delete a substring from a String.
Syntax:
Example:
Output:
6) Using replaceAll method
The replaceAll method, as contrast to replaceFirst, utilizes a regular expression to replace every instance of the string.
Similar to replaceFirst, this method extracts a string using a regular expression by using the compile() and matcher() methods. It also produces a PatternSyntaxException if the regular expression is incorrect.
Syntax:
We will employ a regular expression that pulls out all numbers from a string and substitutes numbers for every instance.
d: This regular expression recognizes any digit between 0 and 9.
Example:
Output:
7) replaceAll() method
With the replaceAll() method, you can use an empty String to remove a substring from a string.
Syntax:
Example:
Output:
Using String Builder’s delete() method
In order to add and remove characters from a string, the StringBuilder holds a modifiable sequence of characters.
A string builder with an initial capacity of 16 characters is created by the empty StringBuilder function Object() { [native code] }, and if the internal buffer overflows, a larger string builder is created automatically.
The start and end of the substring to be deleted from the string are specified as the first and second int parameters of the delete() function.
The last index is exclusive since it subtracts one from the second parameter, but the start index is inclusive.
Syntax:
When the start is negative, bigger than the string’s length, or bigger than the string’s end, a StringIndexOutOfBoundsException is thrown. There are no adjustments done when the start and end are equal.
Example:
Output:
9) Using StringBuilder replace() Method
The sole difference between the replace() function and the delete() method is the third parameter, which is used to replace the characters that have been removed from the string.
If there is a large string that needs to be replaced, the size will be increased to accommodate the length of the string.
Syntax:
The function toString() { [native code] }() function can be used to print the updated string after this method returns a StringBuilder.
Example:
Output:
Conclusion
You’ve learnt how to replace and delete characters to remove a substring from a string in this article. The techniques presented include the use of the StringBuilder delete() and replace() methods, as well as the string replace(), replaceFirst(), and replaceAll() functions.
В этом посте будет обсуждаться, как удалить подстроку из строки, а также заменить подстроку строки другой строкой в Java.
1. Строка replace()
метод
Здесь идея состоит в том, чтобы извлечь подстроку, которую необходимо удалить или заменить, и вызвать метод replace()
метод исходной строки путем передачи подстроки и замены.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
class Main { public static String remove(String text) { // начальный индекс включительно. int beginIndex = text.indexOf(‘ ‘); // конечный индекс, исключительный. int endIndex = text.lastIndexOf(‘ ‘); // получаем подстроку, которую нужно удалить String target = text.substring(beginIndex, endIndex); // заменяем цель пустой строкой return text.replace(target, «»); } public static String replace(String text, String replacement) { // начальный индекс включительно. int beginIndex = text.indexOf(‘(‘) + 1; // конечный индекс, исключительный. int endIndex = text.lastIndexOf(‘)’); // получаем подстроку, которую нужно заменить String target = text.substring(beginIndex, endIndex); return text.replace(target, replacement); } public static void main(String[] args) { String str = «Java (SE Development Kit) 8»; System.out.println(remove(str)); System.out.println(replace(str, «SDK»)); } } |
Скачать Выполнить код
результат:
Java 8
Java (SDK) 8
2. Использование Apache Commons Lang
Мы также можем использовать Apache Commons StringUtils
remove()
метод. Логика остается той же, что и в приведенном выше решении.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import org.apache.commons.lang3.StringUtils; class Main { public static String remove(String text) { // начальный индекс включительно. int beginIndex = text.indexOf(‘ ‘); // конечный индекс, исключительный. int endIndex = text.lastIndexOf(‘ ‘); // получаем подстроку, которую нужно удалить String removeString = text.substring(beginIndex, endIndex); return StringUtils.remove(text, removeString); } public static String replace(String text, String replacement) { // начальный индекс включительно. int beginIndex = text.indexOf(‘(‘) + 1; // конечный индекс, исключительный. int endIndex = text.lastIndexOf(‘)’); // ищем подстроку, которую нужно заменить String searchString = text.substring(beginIndex, endIndex); return StringUtils.replace(text, searchString, replacement); } public static void main(String[] args) { String str = «Java (SE Development Kit) 8»; System.out.println(remove(str)); System.out.println(replace(str, «SDK»)); } } |
Скачать код
результат:
Java 8
Java (SDK) 8
Это все об удалении или замене подстроки в Java.
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂
Let’s see different ways to remove the first word from String in Java.
Remove the first word from String in Java using String’s substring() method
String originalString = "Hello world!";
String newString = originalString.substring(originalString.indexOf(" ") + 1);
This code takes the original string “Hello world!” and uses the indexOf()
method to find the index of the first space character in the string (which is at index 5). It then adds 1 to that index to get the starting index of the substring we want to extract (which is index 6). Finally, it uses the substring()
method to extract the portion of the string starting at index 6 and ending at the end of the string, which is the word “world”
Using String’s join() method
String originalString = "Hello world!";
String[] words = originalString.split(" ");
String newString = String.join(" ", Arrays.copyOfRange(words, 1, words.length));
Using String replaceFirst() method
String originalString = "Hello world!";
String newString = originalString.replaceFirst("[^ ]+ ", "");
Another example
String originalString = "Hello world!";
String newString = originalString.replaceFirst("\b\w+\b", "");
Using String split() method
String originalString = "Hello world!";
System.out.println(Arrays.toString(originalString .split(" ", 2)));
The “best” way to remove the first word from a String in Java depends on the specific requirements of your use case. However, I can provide some guidelines to help you choose the most appropriate method:
- Method 1 (
substring()
): This method is simple and straightforward. However, it assumes that the input string contains at least one space character, and it does not handle the case where the input string is empty. If you know for sure that the input string will always contain a space character and will not be empty, then this method is a good choice. - Method 2 (
split()
): This method is more robust than Method 1, as it can handle cases where the input string is empty or does not contain a space character. However, it creates an array of strings and then joins them again, which may not be the most efficient solution for large strings. - Method 3 (
replaceFirst()
): This method uses regular expressions to remove the first word of the string. It is a concise solution that can handle edge cases well. However, it may be slower than some of the other methods due to the regular expression processing. - Method 4 (
replace()
with regular expression): This method is similar to Method 3, but it replaces all occurrences of the first word in the string rather than just the first occurrence. It is a good choice if you want to remove all occurrences of a specific word in a string. - Method 5 (
substring()
withindexOf()
andlength()
): This method is similar to Method 1, but it is more verbose. However, it may be slightly more efficient than Method 1 because it avoids creating a new string object.
In general, Method 2 is a good choice if you need a robust solution that can handle edge cases. Methods 3 and 4 are good choices if you need to remove a specific word rather than just the first word. Method 1 or Method 5 may be a good choice if you know for sure that the input string will always contain a space character and will not be empty, and you want a simple and straightforward solution.
That’s all about How to remove first word from String in Java.
Related post.
- CollectionUtils isEmpty() Example in Java.
- StringUtils isEmpty() and IsBlank() Example in Java.
- StringUtils join() Example in Java.
- CollectionUtils union() Example in Java
- CollectionUtils intersection() Example in Java
- CollectionUtils isEqualCollection() Example in Java
- StringUtils isAlpha() example in Java
- StringUtils isNumeric() example in Java
In this post, we will see how to delete words from the sentence.
You can just use String’s replaceAll method to replace the word with empty String(«»).
Here is simple java program to delete words from the sentence.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.Scanner; public class StringOperator { public static void main(String args[]) { String str, word; Scanner scan = new Scanner(System.in); System.out.print(«Enter a String : «); str = scan.nextLine(); System.out.print(«Enter a Word you want to Delete from the String : «); word = scan.nextLine(); str = str.replaceAll(word, «»); System.out.print(«nNew String is : «); System.out.print(str); } } |
Output:
Enter a String : Java2Blog is a technical blog.
Enter a Word you want to Delete from the String : technicalNew String is : Java2Blog is a blog.