Java: Remove numbers from string - java

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);
}

Related

Java String.replace() - replaces more than just the substring I specify?

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;
}

Trim leading or trailing characters from a string?

How can I trim the leading or trailing characters from a string in java?
For example, the slash character "/" - I'm not interested in spaces, and am looking to trim either leading or trailing characters at different times.
You could use
Leading:
System.out.println("//test/me".replaceAll("^/+", ""));
Trailing:
System.out.println("//test/me//".replaceAll("/+$", ""));
You can use Apache StringUtils.stripStart to trim leading characters, or StringUtils.stripEnd to trim trailing characters.
For example:
System.out.println(StringUtils.stripStart("//test/me", "/"));
will output:
test/me
Note that if for some reason you can't use the whole StringUtils library, you could just rip out the relevant parts, as detailed here:
Trim with Character, String, or Regex
If run-time is not a big issue for you, then this code will prove really helpful.
public class StringTrimmer {
public static String trim(String string, char ch){
return trim(string, ch, ch);
}
public static String trim(String string, char leadingChar, char trailingChar){
return string.replaceAll("^["+leadingChar+"]+|["+trailingChar+"]+$", "");
}
public static String trim(String string, String regex){
return trim(string, regex, regex);
}
public static String trim(String string, String leadingRegex, String trailingRegex){
return string.replaceAll("^("+leadingRegex+")+|("+trailingRegex+")+$", "");
}
// test
public static void main(String[] args) {
System.out.println(trim("110100", '1', '0')); // outputs: 01
System.out.println(trim("**Aa0*#**", '*')); // outputs: Aa0*#
System.out.println(trim("123##22222", "12", "22")); // outputs: 3##2
System.out.println(trim("101101##10101", "101")); // outputs: ##10
System.out.println(trim("123##abcde", "\\d", "[c-e]")); // outputs: ##ab
}
}
You could use a simple iteration if you want to remove the leading characters from a string :
String removeLeadingChar(String s, char c) {
int i;
for(i = 0; i < s.length() && s.charAt(i) == c; ++i);
return s.substring(i);
}
same logic applies if you want to remove any trailing char.
For those using Spring:
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/StringUtils.html#trimTrailingCharacter-java.lang.String-char-
import org.springframework.util.StringUtils;
public void setFileName(String fileName) {
// If the extension does not exist trim the trailing period
this.fileName = StringUtils.trimTrailingCharacter(fileName,'.');
}
My version of trimming leading and/or trailing String s from String str. Both arguments may be null. When str does not has leading and/or trailing s, it is not changed.
String trim(String str, String s) {
String res = s == null ? str : str == null ? null : s.length() >= str.length() ? str : str.replaceFirst(s, "");
if ((res != null) && (s != null) && (res.length() >= s.length())) {
return res.substring(res.length() - s.length(), res.length()).equals(s) ? res.substring(0, res.length() - s.length()) : res;
}
return res;
}

uppercase 1st character the string [duplicate]

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;
}

Is it possible to use the number of current replacement in String.replaceAll?

Is it possible to make String.replaceAll put the number (count) of the current replacement into the replacement being made?
So that "qqq".replaceAll("(q)", "something:$1 ") would result in "1:q 2:q 3:q"?
Is there anything that I can replace something in the code above with, to make it resolve into the current substitution count?
Here is one way of doing this:
StringBuffer resultString = new StringBuffer();
String subjectString = new String("qqqq");
Pattern regex = Pattern.compile("q");
Matcher regexMatcher = regex.matcher(subjectString);
int i = 1;
while (regexMatcher.find()) {
regexMatcher.appendReplacement(resultString, i+":"+regexMatcher.group(1)+" ");
i++;
}
regexMatcher.appendTail(resultString);
System.out.println(resultString);
See it
No, not with the replaceAll method. The only backreference is \n where n is the n'th capturing group matched.
For this you have to create your own replaceAll() method.
This helps you:
public class StartTheClass
{
public static void main(String[] args)
{
String string="wwwwww";
System.out.println("Replaced As: \n"+replaceCharector(string, "ali:", 'w'));
}
public static String replaceCharector(String original, String replacedWith, char toReplaceChar)
{
int count=0;
String str = "";
for(int i =0; i < original.length(); i++)
{
if(original.charAt(i) == toReplaceChar)
{
str += replacedWith+(count++)+" ";//here add the 'count' value and some space;
}
else
{
str += original.charAt(i);
}
}
return str;
}
}
The output I got is:
Replaced As:
ali:0 ali:1 ali:2 ali:3 ali:4 ali:5

How do i remove the whitespace?

I'm trying to create a palindrome tester program for my AP Java class and I need to remove the white spaces in my code completely but it's not letting me do so.
import java.util.Scanner;
public class Palin{
public static boolean isPalindrome(String stringToTest) {
String workingCopy = removeJunk(stringToTest);
String reversedCopy = reverse(workingCopy);
return reversedCopy.equalsIgnoreCase(workingCopy);
}
public static String removeJunk(String string) {
int i, len = string.length();
StringBuffer dest = new StringBuffer(len);
char c;
for (i = (len - 1); i >= 0; i-=1) {
c = string.charAt(i);
if (Character.isLetterOrDigit(c))
{
dest.append(c);
}
}
return dest.toString();
}
public static String reverse(String string) {
StringBuffer sb = new StringBuffer(string);
return sb.reverse().toString();
}
public static void main(String[] args) {
System.out.print("Enter Palindrome: ");
Scanner sc = new Scanner(System.in);
String string = sc.next();
String str = string;
String space = "";
String result = str.replaceAll("\\W", space);
System.out.println(result);
System.out.println();
System.out.println("Testing palindrome:");
System.out.println(" " + string);
System.out.println();
if (isPalindrome(result)) {
System.out.println("It's a palindrome!");
} else {
System.out.println("Not a palindrome!");
}
System.out.println();
}
}
Any help would be greatly appreciated.
Seems like your code is fine except for the following. You are using
String string = sc.next();
which will not read the whole line of input, hence you will lose part of the text. I think you should use the following instead of that line.
String string = sc.nextLine();
If you just want to remove the beginning and ending whitespace, you can use the built in function trim(), e.g. " abcd ".trim() is "abcd"
If you want to remove it everywhere, you can use the replaceAll() method with the whitespace class as the parameter, e.g. " abcd ".replaceAll("\W","").
Use a StringTokenizer to remove " "
StringTokenizer st = new StringTokenizer(string," ",false);
String t="";
while (st.hasMoreElements()) t += st.nextElement();
String result = t;
System.out.println(result);
I haven't actually tesed this, but have you considered the String.replaceAll(String regex, String replacement) method?
public static String removeJunk (String string) {
return string.replaceAll (" ", "");
}
Another thing to look out for is that while removing all non-digit/alpha characters removeJunk also reverses the string (it starts from the end and then appends one character at a time).
So after reversing it again (in reverse) you are left with the original and it will always claim that the given string is a palindrome.
You should use the String replace(char oldChar, char newChar) method.
Although the name suggests that only the first occurrence will be replaced, fact is that all occurrences will be replaced. The advantage of this method is that it won't use regular expressions, thus is more efficient.
So give a try to string.replace(' ', '');

Categories

Resources