delete dynamic character from string - java

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

Related

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

Java String TRIM function not working

I am receiving a string from server trailing one or two lines of spaces like below given string.
String str = "abc*******
********";
Consider * as spaces after my string
i have tried a few methods like
str = str.trim();
str = str.replace(String.valueOf((char) 160), " ").trim();
str = str.replaceAll("\u00A0", "");
but none is working.
Why i am not able to remove the space?
You should try like this:
str = str.replaceAll("\n", "").trim();
You can observe there is a new line in that string . first replace new line "\n" with space("") and than trim
You should do:
str = str.replaceAll("\n", "");
In my case use to work the function trim()
Try this:
str = str.replaceAll("[.]*[\\s\t]+$", "");
I have tried your 3 methods, and them all work. I think your question describing not correctly or complete, in fact, a String in java would not like
String str = "abc*******
********";
They must like
String str = "abc*******"
+ "********";
So I think you should describe your question better to get help.

Removing certain characters in a string

I want to remove the equal sign in the string below.
String str = "[=Ind(\"Blr-ind\",\"Company\")]";
You can also use String.replaceAll() to replace all occurrences by any other String
String input = "[=Ind(\"Blr-ind\",\"Company\")]";
input = input.replaceAll("=", "");
System.out.println(input);
Use String.replaceFirst() on the string:
String input = "[=Ind(\"Blr-ind\",\"Company\")]";
input = input.replaceFirst("=", "");
System.out.println(input);
Output:
[Ind("Blr-ind","Company")]
just use the replace method :
String s = "[=Ind(\"Blr-ind\",\"C=ompany\")]";
s = s.replace("=", "");

How to concatenate a String in Java without using a complex code structure?

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.

Split a string in java

I am getting this string from a program
[user1, user2]
I need it to be splitted as
String1 = user1
String2 = user2
You could do this to safely remove any brackets or spaces before splitting on commas:
String input = "[user1, user2]";
String[] strings = input.replaceAll("\\[|\\]| ", "").split(",");
// strings[0] will have "user1"
// strings[1] will have "user2"
Try,
String source = "[user1, user2]";
String data = source.substring( 1, source.length()-1 );
String[] split = data.split( "," );
for( String string : split ) {
System.out.println(string.trim());
}
This will do your job and you will receive an array of string.
String str = "[user1, user2]";
str = str.substring(1, str.length()-1);
System.out.println(str);
String[] str1 = str.split(",");
Try the String.split() methods.
From where you are getting this string.can you check the return type of the method.
i think the return type will be some array time and you are savings that return value in string . so it is appending [ ]. if it is not the case you case use any of the methods the users suggested in other answers.
From the input you are saying I think you are already getting an array, don't you?
String[] users = new String[]{"user1", "user2"};
System.out.println("str="+Arrays.toString(str));//this returns your output
Thus having this array you can get them using their index.
String user1 = users[0];
String user2 = users[1];
If you in fact are working with a String then proceed as, for example, #WhiteFang34 suggests (+1).

Categories

Resources