I have a string like 23.Piano+trompet, and i wanted to remove the 23. part from the string using this function:
private String removeSignsFromName(String name) {
name = name.replaceAll(" ", "");
name = name.replaceAll(".", "");
return name.replaceAll("\\^([0-9]+)", "");
}
But it doesn't do it. Also, there is no error in runtime.
The following replaces all whitespace characters (\\s), dots (\\.), and digits (\\d) with "":
name.replaceAll("^[\\s\\.\\d]+", "");
what if I want to replace the + with _?
name.replaceAll("^[\\s\\.\\d]+", "").replaceAll("\\+", "_");
You don't need to escape the ^, you can use \\d+ to match multiple digits, and \\. for a literal dot and you don't need multiple calls to replaceAll. For example,
private static String removeSignsFromName(String name) {
return name.replaceAll("^\\d+\\.", "");
}
Which I tested like
public static void main(String[] args) {
System.out.println(removeSignsFromName("23.Piano+trompet"));
}
And got
Piano+trompet
Two problems:
The . in the second replaceAll should be escaped:
name=name.replaceAll("\\.", "");
The ^ in the third one should NOT be escaped:
return name.replaceAll("^([0-9]+)", "");
Oh! and the parentheses are useless since you don't use the captured string.
How about this:
public static String removeNumOfStr(String str) {
if (str == null) {
return null;
}
char[] ch = str.toCharArray();
int length = ch.length;
StringBuilder sb = new StringBuilder();
int i = 0;
while (i < length) {
if (Character.isDigit(ch[i])) {
i++;
} else {
sb.append(ch[i]);
i++;
}
}
return sb.toString();
}
return name.replaceFirst("^\\d+\\.", "");
public static void removenum(String str){
char[] arr=str.toCharArray();
String s="";
for(char ch:arr){
if(!(ch>47 & ch<57)){
s=s+ch;
}
}
System.out.println(s);
}
As per this CodingBat problem I am trying to do the following:
Given a string, if the first or last chars are 'x', return the string without those 'x' chars, and otherwise return the string unchanged.
My code:
public String withoutX(String str) {
if (str.startsWith("x")) {
str = str.replace(str.substring(0, 1), "");
}
if (str.endsWith("x")) {
str = str.replace(str.substring(str.length()-1), "");
}
return str;
}
This code replaces ALL the x characters in the string, rather than just the first and last. Why does this happen, and what would be a good way to solve it?
You could use string.replaceAll function.
string.replaceAll("^x|x$", "");
The above code will replace the x which was at the start or at the end. If there is no x at the start or at the end, it would return the original string unchanged.
From the sdk for the replace method:
Returns a new string resulting from replacing all occurrences of
oldChar in this string with newChar.
You can solve this without replace:
public String withoutX(String str) {
if (str == null) {
return null;
}
if (str.startsWith("x")) {
str = str.substring(1);
}
if (str.endsWith("x")) {
str = str.substring(0, str.length()-1);
}
return str;
}
You can use replaceFirst for first character or you can substring both side by 1 character
public static String withoutX(String str) {
if (str.startsWith("x")) {
str = str.replaceFirst("x", "");
}
if (str.endsWith("x")) {
str = str.substring(0,str.length() - 1);
}
return str;
}
The trim() function removes both the trailing and leading space, however, if I only want to remove the trailing space of a string, how can I do it?
Since JDK 11
If you are on JDK 11 or higher you should probably be using stripTrailing().
Earlier JDK versions
Using the regular expression \s++$, you can replace all trailing space characters (includes space and tab characters) with the empty string ("").
final String text = " foo ";
System.out.println(text.replaceFirst("\\s++$", ""));
Output
foo
Online demo.
Here's a breakdown of the regex:
\s – any whitespace character,
++ – match one or more of the previous token (possessively); i.e., match one or more whitespace character. The + pattern is used in its possessive form ++, which takes less time to detect the case when the pattern does not match.
$ – the end of the string.
Thus, the regular expression will match as much whitespace as it can that is followed directly by the end of the string: in other words, the trailing whitespace.
The investment into learning regular expressions will become more valuable, if you need to extend your requirements later on.
References
Java regular expression syntax
Another option is to use Apache Commons StringUtils, specifically StringUtils.stripEnd
String stripped = StringUtils.stripEnd(" my lousy string "," ");
I modified the original java.lang.String.trim() method a bit and it should work:
public String trim(String str) {
int len = str.length();
int st = 0;
char[] val = str.toCharArray();
while ((st < len) && (val[len - 1] <= ' ')) {
len--;
}
return str.substring(st, len);
}
Test:
Test test = new Test();
String sample = " Hello World "; // A String with trailing and leading spaces
System.out.println(test.trim(sample) + " // No trailing spaces left");
Output:
Hello World // No trailing spaces left
As of JDK11 you can use stripTrailing:
String result = str.stripTrailing();
The most practical answer is #Micha's, Ahmad's is reverse of what you wanted so but here's what I came up with in case you'd prefer not to use unfamiliar tools or to see a concrete approach.
public String trimEnd( String myString ) {
for ( int i = myString.length() - 1; i >= 0; --i ) {
if ( myString.charAt(i) == ' ' ) {
continue;
} else {
myString = myString.substring( 0, ( i + 1 ) );
break;
}
}
return myString;
}
Used like:
public static void main( String[] args ) {
String s = " Some text here ";
System.out.println( s + "|" );
s = trimEnd( s );
System.out.println( s + "|" );
}
Output:
Some text here |
Some text here|
The best way in my opinion:
public static String trimEnd(String source) {
int pos = source.length() - 1;
while ((pos >= 0) && Character.isWhitespace(source.charAt(pos))) {
pos--;
}
pos++;
return (pos < source.length()) ? source.substring(0, pos) : source;
}
This does not allocate any temporary object to do the job and is faster than using a regular expression. Also it removes all whitespaces, not just ' '.
Here's a very short, efficient and easy-to-read version:
public static String trimTrailing(String str) {
if (str != null) {
for (int i = str.length() - 1; i >= 0; --i) {
if (str.charAt(i) != ' ') {
return str.substring(0, i + 1);
}
}
}
return str;
}
As an alternative to str.charAt(i) != ' ' you can also use !Character.isWhitespace(str.charAt(i) if you want to use a broader definition of whitespace.
Spring framework gives a useful org.springframework.util.StringUtils.
trimTrailingWhitespace
This code is intended to be read a easily as possible by using descriptive names (and avoiding regular expressions).
It does use Java 8's Optional so is not appropriate for everyone.
public static String removeTrailingWhitspace(String string) {
while (hasWhitespaceLastCharacter(string)) {
string = removeLastCharacter(string);
}
return string;
}
private static boolean hasWhitespaceLastCharacter(String string) {
return getLastCharacter(string)
.map(Character::isWhitespace)
.orElse(false);
}
private static Optional<Character> getLastCharacter(String string) {
if (string.isEmpty()) {
return Optional.empty();
}
return Optional.of(string.charAt(string.length() - 1));
}
private static String removeLastCharacter(String string) {
if (string.isEmpty()) {
throw new IllegalArgumentException("String must not be empty");
}
return string.substring(0, string.length() - 1);
}
String value= "Welcome to java ";
So we can use
value = value.trim();
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
String replace method is not working
public static String capitalise(String str)
{
if (str != null || !"".equals(str))
{
char chr=str.charAt(0);
String check= Character.toString(chr);
String check1= check.toUpperCase();
char chr1=check1.charAt(0);
str=str.replace(chr, chr1);
return str;
}
else
{
System.out.println("Not a valid String");
}
return str;
}
i want to uppercase only the first character but it capitalize the first character where it comes for eg before upeercase string = shashank after it becomes ShaShank...what should i do for it .
str.replace(chr, chr1); replaces all occurences of the char in that string. It will change all s to S in your case.
User substring to concatenate the upper-cased first char with the rest of the string.
Here's a simple solution for the additional question in your comment. It will uppercase each character after a single(!) space. You may want to enhance it to allow mulitple spaces or multiple whitechars in general.
public static void main(final String[] args) {
String s = "some words";
StringBuilder result = new StringBuilder();
boolean capitalizeNextLetter = true;
for (char c : s.toCharArray()) {
if (capitalizeNextLetter) {
result.append(Character.toUpperCase(c));
capitalizeNextLetter = false;
} else {
if (c == ' ') {
capitalizeNextLetter = true;
}
result.append(c);
}
}
System.out.println(result.toString());
}
How about something like:
public static String capitalize(String str) {
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
Why not simply do following
str= Character.toUpperCase(str.charAt(0)) + str.substring(1)
In your code replace method will replace all 's' with 'S'.
Because char contains 's';
Try this answer
public static String capitalise(String str)
{
String test = str.substring(0,1);
test=test.toUpperCase();
System.out.println(test);
String new1= test+str.substring(1,str.length());
return new1;
}
try this
public static String capitalise(String str)
{
if (str != null || !"".equals(str))
{
char chr = str.charAt(0);
String capsString = Character.toString(chr).toUpperCase() + str.substring(1);
return capsString;
}
else
{
System.out.println("Not a valid String");
}
return str;
}
Use ReplaceFirst method.
str=str.replaceFirst(check, chreck1);
replaceFirst
Also, you should change your if condition to following:
if (str != null && !"".equals(str))
This way empty string won't be processed.
Try this.just change one line.
public static String capitalise(String str)
{
if (str != null || !"".equals(str))
{
char chr=str.charAt(0);
String check= Character.toString(chr);
String check1= check.toUpperCase();
str=check1+str.substring(1);
return str;
}
else
{
System.out.println("Not a valid String");
}
return str;
}
I want to remove the last character from a string. I've tried doing this:
public String method(String str) {
if (str.charAt(str.length()-1)=='x'){
str = str.replace(str.substring(str.length()-1), "");
return str;
} else{
return str;
}
}
Getting the length of the string - 1 and replacing the last letter with nothing (deleting it), but every time I run the program, it deletes middle letters that are the same as the last letter.
For example, the word is "admirer"; after I run the method, I get "admie." I want it to return the word admire.
replace will replace all instances of a letter. All you need to do is use substring():
public String method(String str) {
if (str != null && str.length() > 0 && str.charAt(str.length() - 1) == 'x') {
str = str.substring(0, str.length() - 1);
}
return str;
}
Why not just one liner?
public static String removeLastChar(String str) {
return removeLastChars(str, 1);
}
public static String removeLastChars(String str, int chars) {
return str.substring(0, str.length() - chars);
}
Full Code
public class Main {
public static void main (String[] args) throws java.lang.Exception {
String s1 = "Remove Last CharacterY";
String s2 = "Remove Last Character2";
System.out.println("After removing s1==" + removeLastChar(s1) + "==");
System.out.println("After removing s2==" + removeLastChar(s2) + "==");
}
public static String removeLastChar(String str) {
return removeLastChars(str, 1);
}
public static String removeLastChars(String str, int chars) {
return str.substring(0, str.length() - chars);
}
}
Demo
Since we're on a subject, one can use regular expressions too
"aaabcd".replaceFirst(".$",""); //=> aaabc
The described problem and proposed solutions sometimes relate to removing separators. If this is your case, then have a look at Apache Commons StringUtils, it has a method called removeEnd which is very elegant.
Example:
StringUtils.removeEnd("string 1|string 2|string 3|", "|");
Would result in:
"string 1|string 2|string 3"
public String removeLastChar(String s) {
if (s == null || s.length() == 0) {
return s;
}
return s.substring(0, s.length()-1);
}
Don't try to reinvent the wheel, while others have already written libraries to perform string manipulation:
org.apache.commons.lang3.StringUtils.chop()
In Kotlin you can used dropLast() method of the string class.
It will drop the given number from string, return a new string
var string1 = "Some Text"
string1 = string1.dropLast(1)
Use this:
if(string.endsWith("x")) {
string= string.substring(0, string.length() - 1);
}
if (str.endsWith("x")) {
return str.substring(0, str.length() - 1);
}
return str;
For example, the word is "admirer"; after I run the method, I get "admie." I want it to return the word admire.
In case you're trying to stem English words
Stemming is the process for reducing inflected (or sometimes derived) words to their stem, base or root form—generally a written word form.
...
A stemmer for English, for example, should identify the string "cats" (and possibly "catlike", "catty" etc.) as based on the root "cat", and "stemmer", "stemming", "stemmed" as based on "stem". A stemming algorithm reduces the words "fishing", "fished", "fish", and "fisher" to the root word, "fish".
Difference between Lucene stemmers: EnglishStemmer, PorterStemmer, LovinsStemmer outlines some Java options.
As far as the readability is concerned, I find this to be the most concise
StringUtils.substring("string", 0, -1);
The negative indexes can be used in Apache's StringUtils utility.
All negative numbers are treated from offset from the end of the string.
string = string.substring(0, (string.length() - 1));
I'm using this in my code, it's easy and simple.
it only works while the String is > 0.
I have it connected to a button and inside the following if statement
if (string.length() > 0) {
string = string.substring(0, (string.length() - 1));
}
public String removeLastChar(String s) {
if (!Util.isEmpty(s)) {
s = s.substring(0, s.length()-1);
}
return s;
}
removes last occurence of the 'xxx':
System.out.println("aaa xxx aaa xxx ".replaceAll("xxx([^xxx]*)$", "$1"));
removes last occurrence of the 'xxx' if it is last:
System.out.println("aaa xxx aaa ".replaceAll("xxx\\s*$", ""));
you can replace the 'xxx' on what you want but watch out on special chars
Look to StringBuilder Class :
StringBuilder sb=new StringBuilder("toto,");
System.out.println(sb.deleteCharAt(sb.length()-1));//display "toto"
// creating StringBuilder
StringBuilder builder = new StringBuilder(requestString);
// removing last character from String
builder.deleteCharAt(requestString.length() - 1);
How can a simple task be made complicated. My solution is:
public String removeLastChar(String s) {
return s[0..-1]
}
or
public String removeLastChar(String s) {
if (s.length() > 0) {
return s[0..-1]
}
return s
}
// Remove n last characters
// System.out.println(removeLast("Hello!!!333",3));
public String removeLast(String mes, int n) {
return mes != null && !mes.isEmpty() && mes.length()>n
? mes.substring(0, mes.length()-n): mes;
}
// Leave substring before character/string
// System.out.println(leaveBeforeChar("Hello!!!123", "1"));
public String leaveBeforeChar(String mes, String last) {
return mes != null && !mes.isEmpty() && mes.lastIndexOf(last)!=-1
? mes.substring(0, mes.lastIndexOf(last)): mes;
}
A one-liner answer (just a funny alternative - do not try this at home, and great answers already given):
public String removeLastChar(String s){return (s != null && s.length() != 0) ? s.substring(0, s.length() - 1): s;}
Most answers here forgot about surrogate pairs.
For instance, the character 𝕫 (codepoint U+1D56B) does not fit into a single char, so in order to be represented, it must form a surrogate pair of two chars.
If one simply applies the currently accepted answer (using str.substring(0, str.length() - 1), one splices the surrogate pair, leading to unexpected results.
One should also include a check whether the last character is a surrogate pair:
public static String removeLastChar(String str) {
Objects.requireNonNull(str, "The string should not be null");
if (str.isEmpty()) {
return str;
}
char lastChar = str.charAt(str.length() - 1);
int cut = Character.isSurrogate(lastChar) ? 2 : 1;
return str.substring(0, str.length() - cut);
}
Java 8
import java.util.Optional;
public class Test
{
public static void main(String[] args) throws InterruptedException
{
System.out.println(removeLastChar("test-abc"));
}
public static String removeLastChar(String s) {
return Optional.ofNullable(s)
.filter(str -> str.length() != 0)
.map(str -> str.substring(0, str.length() - 1))
.orElse(s);
}
}
Output : test-ab
public String removeLastCharacter(String str){
String result = null;
if ((str != null) && (str.length() > 0)) {
return str.substring(0, str.length() - 1);
}
else{
return "";
}
}
if we want to remove file extension of the given file,
** Sample code
public static String removeNCharactersFromLast(String str,int n){
if (str != null && (str.length() > 0)) {
return str.substring(0, str.length() - n);
}
return "";
}
For kotlin check out
string.dropLast(1)
if you have special character like ; in json just use String.replace(";", "") otherwise you must rewrite all character in string minus the last.
Why not use the escape sequence ... !
System.out.println(str + '\b');
Life is much easier now . XD ! ~ A readable one-liner
How to make the char in the recursion at the end:
public static String removeChar(String word, char charToRemove)
{
String char_toremove=Character.toString(charToRemove);
for(int i = 0; i < word.length(); i++)
{
if(word.charAt(i) == charToRemove)
{
String newWord = word.substring(0, i) + word.substring(i + 1);
return removeChar(newWord,charToRemove);
}
}
System.out.println(word);
return word;
}
for exemple:
removeChar ("hello world, let's go!",'l') → "heo word, et's go!llll"
removeChar("you should not go",'o') → "yu shuld nt goooo"
Here's an answer that works with codepoints outside of the Basic Multilingual Plane (Java 8+).
Using streams:
public String method(String str) {
return str.codePoints()
.limit(str.codePoints().count() - 1)
.mapToObj(i->new String(Character.toChars(i)))
.collect(Collectors.joining());
}
More efficient maybe:
public String method(String str) {
return str.isEmpty()? "": str.substring(0, str.length() - Character.charCount(str.codePointBefore(str.length())));
}
just replace the condition of "if" like this:
if(a.substring(a.length()-1).equals("x"))'
this will do the trick for you.
Suppose total length of my string=24
I want to cut last character after position 14 to end, mean I want starting 14 to be there.
So I apply following solution.
String date = "2019-07-31T22:00:00.000Z";
String result = date.substring(0, date.length() - 14);
I had to write code for a similar problem. One way that I was able to solve it used a recursive method of coding.
static String removeChar(String word, char charToRemove)
{
for(int i = 0; i < word.lenght(); i++)
{
if(word.charAt(i) == charToRemove)
{
String newWord = word.substring(0, i) + word.substring(i + 1);
return removeChar(newWord, charToRemove);
}
}
return word;
}
Most of the code I've seen on this topic doesn't use recursion so hopefully I can help you or someone who has the same problem.