This question already has answers here:
How to remove only trailing spaces of a string in Java and keep leading spaces?
(10 answers)
Closed 5 years ago.
i already found similar topics but they were not really helpful.
I basically need to know how I can remove whitespaces ONLY at the end of a string.
For example: String a = "Good Morning it is a nice day ";
Should be: String a = "Good Morning it is a nice day";
You see there are like three whitespaces at the end or something. I got replaceAll() as a suggestion but as I said I only want to remove the remaining whitespaces at the end. How do I do that ? I already tried different things like going through the String like this:
for(int i = a.length(); i > a.length() - 3; i++){
if(a.charAt(i) == ' '){
<insert Solution here>
}
}
With the code above I wanted to check the last three Chars of the string because it is sufficient. It is sufficient for the stuff I want to do. There wont be a case with 99+ whitespaces at the end (probably).
But as you see I still dont know which method to use or if this is actually the right way.
Any suggestions please ?
If your goal is to cut only the trailing white space characters and to save leading white space characters of your String, you can use String class' replaceFirst() method:
String yourString = " my text. ";
String cutTrailingWhiteSpaceCharacters = yourString.replaceFirst("\\s++$", "");
\\s++ - one or more white space characters (use of possesive quantifiers (take a look at Pattern class in the Java API documentation, you have listed all of the special characters used in reguĊar expressions there)),
$ - end of string
You might also want to take a look at part of my answer before the edit:
If you don't care about the leading white space characters of your input String:
String class provides a trim() method. It might be quick solution in your case as it cuts leading and trailing whitespaces of the given String.
You can either use the regular expression:
a = a.replaceAll("\\s+$", "");
to remove trailing whitespaces and store the result back into a
or using a for loop:
String a = "Good Morning it is a nice day ";
StringBuilder temp = new StringBuilder(a);
for( int i = temp.length() - 1 ; i >= 0; i--){
if(temp.charAt(i) == ' '){
temp.deleteCharAt(i);
}else{
break;
}
}
a = temp.toString();
a = ("X" + a).trim().substring(1);
int counter = 0;
String newWord = "";
for(int i = 0; i < word.length(); i++){
if (word.charAt(i) == " "){
counter++;
}
else {
counter = 0;
}
if (counter > 1){
newWord = word.substring(0, i);
break;
}
else {
newWord = word;
}
}
The solution would look something like this.
I was working on some string formatting, and I was curious if I was doing it the most efficient way.
Assume I have a String Array:
String ArrayOne[] = {"/test/" , "/this/is/test" , "/that/is/" "/random/words" }
I want the result Array to be
String resultArray[] = {"test", "this_is_test" , "that_is" , "random_words" }
It's quite messy and brute-force-like.
for(char c : ArrayOne[i].toCharArray()) {
if(c == '/'){
occurances[i]++;
}
}
First I count the number of "/" in each String like above and then using these counts, I find the indexOf("/") for each string and add "_" accordingly.
As you can see though, it gets very messy.
Is there a more efficient way to do this besides the brute-force way I'm doing?
Thanks!
You could use replaceAll and replace, as follows:
String resultArray[] = new String[ArrayOne.length];
for (int i = 0; i < ArrayOne.length; ++i) {
resultArray[i] = ArrayOne[i].replaceAll("^/|/$", "").replace('/', '_');
}
The replaceAll method searches the string for a match to the regex given in the first argument, and replaces each match with the text in the second argument.
Here, we use it first to remove leading and trailing slashes. We search for slashes at the start of the string (^/) or the end of the string (/$), and replace them with nothing.
Then, we replace all remaining slashes with underscores using replace.
I have the following string:
String n = "(.........)(......)(.......)(......) etc"
I want to write a method which will fill a List<String> with every substring of n which is between ( and ) . Thank you in advance!
It can be done in one line:
String[] parts = input.replaceAll("(^.*\\()|(\\).*$)", "").split("\\)\\(");
The call to replaceAll() strips off the leasing and trailing brackets (plus any other junk characters before/after those first/last brackets), then you just split() on bracket pairs.
I'm not very familiar with the String methods, so I'm sure there's a way that it could be done without having to code it yourself, and just using some fancy method, but here you go:
Tested, works 100% perfect :)
String string = "(stack)(over)(flow)";
ArrayList<String> subStrings = new ArrayList<String>();
for(int c = 0; c < string.length(); c++) {
if(string.charAt(c) == '(') {
c++;
String newString = "";
for(;c < string.length() && string.charAt(c) != ')'; c++) {
newString += string.charAt(c);
}
subStrings.add(newString);
}
}
If the (...) pairs aren't nested, you can use a regular expression in Java. Take a look at the java.util.regex.Pattern class.
I made this regex version, but it's kind of lengthy. I'm sure it could be improved upon. (note: "n" is your input string)
Pattern p = Pattern.compile("\\((.*?)\\)");
Matcher matcher = p.matcher(n);
List<String> list = new ArrayList<String>();
while (matcher.find())
{
list.add(matcher.group(1)); // 1 == stuff between the ()'s
}
This should work:
String in = "(bla)(die)(foo)";
in = in .substring(1,in.length()-1);
String[] out = in .split(Pattern.quote(")("));
I'm using the scanner method to do work on a string and need to filter out junk
here's the sample string
5/31/1948#14:57
I need to strip out the / # :
Theres this doc: http://download.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html
But it's really confusing.
You can use the replaceAll method as:
String filetredStr = inputStr.replaceAll("[#/:]","");
And if you want to delete any non-digit you can do:
String filetredStr = inputStr.replaceAll("[^0-9]","");
If you're looking to split it up, use String#split()
String[] parts = "5/31/1948#14:57".split("[/#:]");
Do something like this:-
s.replaceAll("[\\/#:]", "");
An alternative to replaceAll(a,b) is as follows:
String str = "5/31/1948#14:57";
String charsToRemove = "/#:";
for (int i = 0; i < charsToRemove.length(); i++) {
str = str.replace(charsToRemove.charAt(i)+"", "");
}
I would like to trim a beginning and ending double quote (") from a string.
How can I achieve that in Java? Thanks!
You can use String#replaceAll() with a pattern of ^\"|\"$ for this.
E.g.
string = string.replaceAll("^\"|\"$", "");
To learn more about regular expressions, have al ook at http://regular-expression.info.
That said, this smells a bit like that you're trying to invent a CSV parser. If so, I'd suggest to look around for existing libraries, such as OpenCSV.
To remove the first character and last character from the string, use:
myString = myString.substring(1, myString.length()-1);
Also with Apache StringUtils.strip():
StringUtils.strip(null, *) = null
StringUtils.strip("", *) = ""
StringUtils.strip("abc", null) = "abc"
StringUtils.strip(" abc", null) = "abc"
StringUtils.strip("abc ", null) = "abc"
StringUtils.strip(" abc ", null) = "abc"
StringUtils.strip(" abcyx", "xyz") = " abc"
So,
final String SchrodingersQuotedString = "may or may not be quoted";
StringUtils.strip(SchrodingersQuotedString, "\""); //quoted no more
This method works both with quoted and unquoted strings as shown in my example. The only downside is, it will not look for strictly matched quotes, only leading and trailing quote characters (ie. no distinction between "partially and "fully" quoted strings).
If the double quotes only exist at the beginning and the end, a simple code as this would work perfectly:
string = string.replace("\"", "");
Kotlin
In Kotlin you can use String.removeSurrounding(delimiter: CharSequence)
E.g.
string.removeSurrounding("\"")
Removes the given delimiter string from both the start and the end of this string if and only if it starts with and ends with the delimiter.
Otherwise returns this string unchanged.
The source code looks like this:
public fun String.removeSurrounding(delimiter: CharSequence): String = removeSurrounding(delimiter, delimiter)
public fun String.removeSurrounding(prefix: CharSequence, suffix: CharSequence): String {
if ((length >= prefix.length + suffix.length) && startsWith(prefix) && endsWith(suffix)) {
return substring(prefix.length, length - suffix.length)
}
return this
}
This is the best way I found, to strip double quotes from the beginning and end of a string.
someString.replace (/(^")|("$)/g, '')
First, we check to see if the String is doubled quoted, and if so, remove them. You can skip the conditional if in fact you know it's double quoted.
if (string.length() >= 2 && string.charAt(0) == '"' && string.charAt(string.length() - 1) == '"')
{
string = string.substring(1, string.length() - 1);
}
Using Guava you can write more elegantly CharMatcher.is('\"').trimFrom(mystring);
I am using something as simple as this :
if(str.startsWith("\"") && str.endsWith("\""))
{
str = str.substring(1, str.length()-1);
}
To remove one or more double quotes from the start and end of a string in Java, you need to use a regex based solution:
String result = input_str.replaceAll("^\"+|\"+$", "");
If you need to also remove single quotes:
String result = input_str.replaceAll("^[\"']+|[\"']+$", "");
NOTE: If your string contains " inside, this approach might lead to issues (e.g. "Name": "John" => Name": "John).
See a Java demo here:
String input_str = "\"'some string'\"";
String result = input_str.replaceAll("^[\"']+|[\"']+$", "");
System.out.println(result); // => some string
Edited: Just realized that I should specify that this works only if both of them exists. Otherwise the string is not considered quoted. Such scenario appeared for me when working with CSV files.
org.apache.commons.lang3.StringUtils.unwrap("\"abc\"", "\"") = "abc"
org.apache.commons.lang3.StringUtils.unwrap("\"abc", "\"") = "\"abc"
org.apache.commons.lang3.StringUtils.unwrap("abc\"", "\"") = "abc\""
The pattern below, when used with java.util.regex.Matcher, will match any string between double quotes without affecting occurrences of double quotes inside the string:
"[^\"][\\p{Print}]*[^\"]"
Matcher m = Pattern.compile("^\"(.*)\"$").matcher(value);
String strUnquoted = value;
if (m.find()) {
strUnquoted = m.group(1);
}
Modifying #brcolow's answer a bit
if (string != null && string.length() >= 2 && string.startsWith("\"") && string.endsWith("\"") {
string = string.substring(1, string.length() - 1);
}
private static String removeQuotesFromStartAndEndOfString(String inputStr) {
String result = inputStr;
int firstQuote = inputStr.indexOf('\"');
int lastQuote = result.lastIndexOf('\"');
int strLength = inputStr.length();
if (firstQuote == 0 && lastQuote == strLength - 1) {
result = result.substring(1, strLength - 1);
}
return result;
}
find indexes of each double quotes and insert an empty string there.
public String removeDoubleQuotes(String request) {
return request.replace("\"", "");
}
Groovy
You can subtract a substring from a string using a regular expression in groovy:
String unquotedString = theString - ~/^"/ - ~/"$/
Scala
s.stripPrefix("\"").stripSuffix("\"")
This works regardless of whether the string has or does not have quotes at the start and / or end.
Edit: Sorry, Scala only