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"));
Related
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
I have a string containing numbers separated with ,. I want to remove the , before the first character.
The input is ,1,2,3,4,5,6,7,8,9,10, and this code does not work:
results.replaceFirst(",","");
Strings are immutable in Java. Calling a method on a string will not modify the string itself, but will instead return a new string.
In order to capture this new string, you need to assign the result of the operation back to a variable:
results = results.replaceFirst(",", "");
Try this
String str = ",1,2,3,4,5,6,7,8,9,10";
str = str .startsWith(",") ? str .substring(1) : str ;
System.out.println("output"+str); // 1,2,3,4,5,6,7,8,9,10
you can also do like this ..
String str = ",1,2,3,4,5,6,7,8,9,10";
String stre = str.replaceFirst("^,", "");
Log.e("abd",stre);
Try this
String str = ",1,2,3,4,5,6,7,8,9,10";
if(Objects.nonNull(str) && str.startsWith(",")){
str = str.substring(1, str.length());
}
it will remove , at first position
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);
Example:
cname = "name"
ccurt = "last name"
Required output = name - last name
But current output = namelast name
How to get output as above? The used code is below for your reference,
Code used:
long id= AddDbHelper.createReminder(cname +ccurt,de,reminderDateTime);
use
String output=cname+"-"+ccurt;
I guess you can use StringBuilder
StringBuilder tmp = new StringBuilder();
tmp.append(cname);
tmp.append("-");
tmp.append(ccurt);
String fullName = tmp.toString();
Or simply:
String fullName = new StringBuilder(cname).append(" - ").append(ccurt).toString();
StringBuilder
A modifiable sequence of characters for use in creating strings. This
class is intended as a direct replacement of StringBuffer for
non-concurrent use; unlike StringBuffer this class is not
synchronized.
Simply use
String output=cname+" - "+ccurt;
I have the following java code:
String strTest = null;
for (AlternativeEntity alternativeEntity : msg.Guidance()
.getAlternatives()) {
strTest = strTest + alternativeEntity.getArrivalStation().getName() + ", ";
}
The output looks like this:
nullabc, xyz, oop,
How can I solve this problem and very bad character format? It would be great if I can create output like this:
abc, xyz, oop
Initialize your string to "":
String strTest = "";
Alternatively, you should use a StringBuilder:
StringBuilder builder = new StringBuilder();
for (AlternativeEntity alternativeEntity : msg.Guidance()
.getAlternatives()) {
builder.append(alternativeEntity.getArrivalStation().getName()).append(", ");
}
This will produce better performance.
Initialize strTest as:
String strTest = "";
Also, remove the last comma ,
strTest=strTest.substring(0, strTest.length()-1);
You can use Guava's Joiner#join(Iterable parts). For example:
Joiner joiner = Joiner.on(", ").skipNulls();
String result = joiner.join(list);
System.out.println(result);
Here, all the elements of the list will be printed comma separated without any trailing commas. Also, all the null elements will be skipped.
More info:
Strings Explained
Java provides StringBuilder class just for this purpose,its simple and easy to use..
StringBuilder str = new StringBuilder("India ");
//to append "Hi"
str.append("Hi");
// print the whole string
System.out.println("The string is "+str)
the output will be : The string is India Hi
click here to know more about StringBuilder class
Replace String strTest = null; by String strTest = "";
Change
String strTest = null;
to
String strTest = "";
why don't you use:
String strTest = "";
and at the end:
if(strTest.endsWith(", "))
strTest = strTest.substring(0, strTest.length()-2);
Initialize String strTest="";
For skipping the last comma','
Use outside For loop:
strTest = strTest.substring(0,strTest.trim().length()-1);
String strTest = null;
for (AlternativeEntity alternativeEntity : msg.Guidance().getAlternatives()) {
String name = alternativeEntity.getArrivalStation().getName();
strTest = (strTest == null) ? name : strTest + ", " + name;
}
If the list is long, you should use a StringBuilder rather than the String for strTest because the code above builds a fresh string on each iteration: far too much copying.