Replace section on string in java - java

I have this section of code
String string = "somestring";
String str2 = "str";
String str3 = "xxx"
if ( string.match("(.*)" + str2 + "(.*)") ) {
//
}
result = somxxxing
how can i replace that section of string with str3?
i need this to work for every strings

Check out the javadoc for java.lang.String.
You're probably looking for String.replace(CharSequence target, CharSequence replacement), which replaces every occurrence of target with replacement.
e.g.
result = string.replace(str2, str3);

Related

Why does String.replaceAll(".*", "REPLACEMENT") give unexpected behavior in Java 8?

Java 8's String.replaceAll(regexStr, replacementStr) doesn't work when the regex given is ".*". The result is double the replacementStr. For example:
String regexStr = ".*";
String replacementStr = "REPLACEMENT"
String initialStr = "hello";
String finalStr = initialStr.replaceAll(regexStr, replacementStr);
// Expected Result: finalStr == "REPLACEMENT"
// Actual Result: finalStr == "REPLACEMENTREPLACEMENT"
I know replaceAll() doesn't exactly make sense to use when the regex is ".*", but the regex isn't hardcoded and could be other regex strings. Why doesn't this work? Is it a bug in Java 8?
// specify start and end of line
String regexStr = "^.*$";
String replacementStr = "REPLACEMENT"
String initialStr = "hello";
String finalStr = initialStr.replaceAll(regexStr, replacementStr);

Remove parts of String? [duplicate]

I want to remove a part of string from one character, that is:
Source string:
manchester united (with nice players)
Target string:
manchester united
There are multiple ways to do it. If you have the string which you want to replace you can use the replace or replaceAll methods of the String class. If you are looking to replace a substring you can get the substring using the substring API.
For example
String str = "manchester united (with nice players)";
System.out.println(str.replace("(with nice players)", ""));
int index = str.indexOf("(");
System.out.println(str.substring(0, index));
To replace content within "()" you can use:
int startIndex = str.indexOf("(");
int endIndex = str.indexOf(")");
String replacement = "I AM JUST A REPLACEMENT";
String toBeReplaced = str.substring(startIndex + 1, endIndex);
System.out.println(str.replace(toBeReplaced, replacement));
String Replace
String s = "manchester united (with nice players)";
s = s.replace(" (with nice players)", "");
Edit:
By Index
s = s.substring(0, s.indexOf("(") - 1);
Use String.Replace():
http://www.daniweb.com/software-development/java/threads/73139
Example:
String original = "manchester united (with nice players)";
String newString = original.replace(" (with nice players)","");
originalString.replaceFirst("[(].*?[)]", "");
https://ideone.com/jsZhSC
replaceFirst() can be replaced by replaceAll()
Using StringBuilder, you can replace the following way.
StringBuilder str = new StringBuilder("manchester united (with nice players)");
int startIdx = str.indexOf("(");
int endIdx = str.indexOf(")");
str.replace(++startIdx, endIdx, "");
You should use the substring() method of String object.
Here is an example code:
Assumption: I am assuming here that you want to retrieve the string till the first parenthesis
String strTest = "manchester united(with nice players)";
/*Get the substring from the original string, with starting index 0, and ending index as position of th first parenthesis - 1 */
String strSub = strTest.subString(0,strTest.getIndex("(")-1);
I would at first split the original string into an array of String with a token " (" and the String at position 0 of the output array is what you would like to have.
String[] output = originalString.split(" (");
String result = output[0];
Using StringUtils from commons lang
A null source string will return null. An empty ("") source string will return the empty string. A null remove string will return the source string. An empty ("") remove string will return the source string.
String str = StringUtils.remove("Test remove", "remove");
System.out.println(str);
//result will be "Test"
If you just need to remove everything after the "(", try this. Does nothing if no parentheses.
StringUtils.substringBefore(str, "(");
If there may be content after the end parentheses, try this.
String toRemove = StringUtils.substringBetween(str, "(", ")");
String result = StringUtils.remove(str, "(" + toRemove + ")");
To remove end spaces, use str.trim()
Apache StringUtils functions are null-, empty-, and no match- safe
Kotlin Solution
If you are removing a specific string from the end, use removeSuffix (Documentation)
var text = "one(two"
text = text.removeSuffix("(two") // "one"
If the suffix does not exist in the string, it just returns the original
var text = "one(three"
text = text.removeSuffix("(two") // "one(three"
If you want to remove after a character, use
// Each results in "one"
text = text.replaceAfter("(", "").dropLast(1) // You should check char is present before `dropLast`
// or
text = text.removeRange(text.indexOf("("), text.length)
// or
text = text.replaceRange(text.indexOf("("), text.length, "")
You can also check out removePrefix, removeRange, removeSurrounding, and replaceAfterLast which are similar
The Full List is here: (Documentation)
// Java program to remove a substring from a string
public class RemoveSubString {
public static void main(String[] args) {
String master = "1,2,3,4,5";
String to_remove="3,";
String new_string = master.replace(to_remove, "");
// the above line replaces the t_remove string with blank string in master
System.out.println(master);
System.out.println(new_string);
}
}
You could use replace to fix your string. The following will return everything before a "(" and also strip all leading and trailing whitespace. If the string starts with a "(" it will just leave it as is.
str = "manchester united (with nice players)"
matched = str.match(/.*(?=\()/)
str.replace(matched[0].strip) if matched

How to split a string from the first space occurrence only Java

I tried to split a string using string.Index and string.length but I get an error that string is out of range. How can I fix that?
while (in.hasNextLine()) {
String temp = in.nextLine().replaceAll("[<>]", "");
temp.trim();
String nickname = temp.substring(temp.indexOf(' '));
String content = temp.substring(' ' + temp.length()-1);
System.out.println(content);
Use the java.lang.String split function with a limit.
String foo = "some string with spaces";
String parts[] = foo.split(" ", 2);
System.out.println(String.format("cr: %s, cdr: %s", parts[0], parts[1]));
You will get:
cr: some, cdr: string with spaces
Must be some around this:
String nickname = temp.substring(0, temp.indexOf(' '));
String content = temp.substring(temp.indexOf(' ') + 1);
string.split(" ",2)
split takes a limit input restricting the number of times the pattern is applied.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)
String string = "This is test string on web";
String splitData[] = string.split("\\s", 2);
Result ::
splitData[0] => This
splitData[1] => is test string
String string = "This is test string on web";
String splitData[] = string.split("\\s", 3);
Result ::
splitData[0] => This
splitData[1] => is
splitData[1] => test string on web
By default split method create n number's of arrays on the basis of given regex.
But if you want to restrict number of arrays to create after a split than pass second argument as an integer argument.

Remove first word from a string in Java

What's the best way to remove the first word from a string in Java?
If I have
String originalString = "This is a string";
I want to remove the first word from it and in effect form two strings -
removedWord = "This"
originalString = "is a string;
Simple.
String o = "This is a string";
System.out.println(Arrays.toString(o.split(" ", 2)));
Output :
[This, is a string]
EDIT:
In line 2 below the values are stored in the arr array. Access them like normal arrays.
String o = "This is a string";
String [] arr = o.split(" ", 2);
arr[0] // This
arr[1] // is a string
You can use substring
removedWord = originalString.substring(0,originalString.indexOf(' '));
originalString = originalString.substring(originalString.indexOf(' ')+1);
This will definitely a good solution
String originalString = "This is a string";
originalString =originalString.replaceFirst("This ", "");
Try this using an index var, I think it's quite efficient :
int spaceIdx = originalString.indexOf(" ");
String removedWord = originalString.substring(0,spaceIdx);
originalString = originalString.substring(spaceIdx);
Prior to JDK 1.7 using below method might be more efficient, especially if you are using long string (see this article).
originalString = new String(originalString.substring(spaceIdx));
For an immediate answer you can use this :
removeWord = originalString.substring(0,originalString.indexOf(' '));
originalString = originalString.substring(originalString.indexOf(' '));
You can check where is the first space character and seperate string.
String full = "Sample Text";
String cut;
int pointToCut = full.indexOf( ' ');
if ( offset > -1)
{
cut = full.substring( space + 1);
}
String str = "This is a string";
String str2=str.substring(str.indexOf(" "));
String str3=str.replaceFirst(str2, "");
String's replaceFirst and substring
also you can use this solution:
static String substringer(String inputString, String remove) {
if (inputString.substring(0, remove.length()).equalsIgnoreCase(remove)) {
return inputString.substring(remove.length()).trim();
}
else {
return inputString.trim();
}
}
Example :
substringer("This is a string", "This");
You can use the StringTokenizer class.

how to add a hyphen in between a string

I have the following sting xxxxx, I want to add a hyphen like x-xxxx, how can I do so using Java?
You can make use of String#substring().
String newstring = string.substring(0, 1) + "-" + string.substring(1);
You'll only need to check the string length beforehand to avoid IndexOutOfBoundsException, but that's nothing more than obvious.
Assuming
String in = "ABCDEF";
String out;
Then, any of:
out = in.replaceFirst(".", "$0-");
or
out = String.format("%1$s-%2$s", in.substring(0,1), in.substring(1));
or
out = in.substring(0,1) + "-" + in.substring(1);
or
out = new StringBuilder(in).insert(1, '-').toString();
will make out = "A-BCDEF".
String is an immutable type in Java, meaning that you can't change the character sequence it represents once the String is constructed.
You can use an instance of the StringBuilder class to create a new instance of String that represents some transformation of the original String. For example, add a hyphen, as you ask, you can do this:
String str = "xxxxx";
StringBuilder builder = new StringBuilder(str);
builder.insert(1, '-');
String hyphenated = builder.toString(); // "x-xxxx"
The StringBuilder initially contains a copy of the contents of str; that is, "xxxxx".
The call to insert changes the builder's contents to "x-xxxx".
Calling toString returns a new String containing a copy the contents of the string builder.
Because the String type is immutable, no manipulation of the StringBuilder's contents will ever change the contents of str or hyphenated.
You can change what String instance str refers to by doing
str = builder.toString();
instead of
String hyphenated = builder.toString();
But never has the contents of a string that str refers to changed, because this is not possible. Instead, str used to refer to a instance containing "xxxxx", and now refers to a instance containing "x-xxxx".
String xxx = "xxxxx";
String hyphened = xxx.substring(0,1) + "-" + xxx.substring(1);
You can do:
String orgStr = "xxxxx";
String newStr = orgStr.substring(0,1) + "-" + orgStr.substring(1)
Here's another way:
MaskFormatter fmt = new MaskFormatter("*-****");
fmt.setValueContainsLiteralCharacters(false);
System.out.println(fmt.valueToString("12345"));

Categories

Resources