I try to get only this part "10.135.57.1/24" in "10.135.57.1/24 05492518979" in android. How can I do this?
I tried below to use substring but it can use for get integer How can I get only 10.135.57.1/24 ?
For this string the following approach will work:
String[] parts = "10.135.57.1/24 05492518979".split(" ");
String partThatYouNeed = parts[0];
In the substring method you're defining which subsection of the String you're after.
If you did the following you'd get your result:
String whatYouWant = "10.135.57.1/24 05492518979".substring(0, 14);
Or using substring
String yourString = "10.135.57.1/24 05492518979";
int index = yourString.indexof(" ");
String partThatYouNeed = yourString.substring(0,index);
How about this :-)
"10.135.57.1/24 05492518979".replaceFirst(" \\d+$", "")
or this:
"10.135.57.1/24 05492518979".replaceFirst(" .+$", "")
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 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.
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("=", "");
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.
I need help in trimming a string url.
Let's say the String is http://myurl.com/users/232222232/pageid
What i would like returned would be /232222232/pageid
Now the 'myurl.com' can change but the /users/ will always be the same.
I suggest you use substring and indexOf("/users/").
String url = "http://myurl.com/users/232222232/pageid";
String lastPart = url.substring(url.indexOf("/users/") + 6);
System.out.println(lastPart); // prints "/232222232/pageid"
A slightly more sophisticated variant would be to let the URL class parse the url for you:
URL url = new URL("http://myurl.com/users/232222232/pageid");
String lastPart = url.getPath().substring(6);
System.out.println(lastPart); // prints "/232222232/pageid"
And, a third approach, using regular expressions:
String url = "http://myurl.com/users/232222232/pageid";
String lastPart = url.replaceAll(".*/users", "");
System.out.println(lastPart); // prints "/232222232/pageid"
string.replaceAll(".*/users(/.*/.*)", "$1");
String rest = url.substring(url.indexOf("/users/") + 6);
You can use split(String regex,int limit) which will split the string around the pattern in regex at most limit times, so...
String url="http://myurl.com/users/232222232/pageid";
String[] parts=url.split("/users",1);
//parts={"http://myurl.com","/232222232/pageid"}
String rest=parts[1];
//rest="/232222232/pageid"
The limit is there to prevent strings like "http://myurl.com/users/232222232/users/pageid" giving answers like "/232222232".
You can use String.indexOf() and String.substring() in order to achieve this:
String pattern = "/users/";
String url = "http://myurl.com/users/232222232/pageid";
System.out.println(url.substring(url.indexOf(pattern)+pattern.length()-1);