Removing Dollar and comma from string - java

How can we remove dollar sign ($) and all comma(,) from same string? Would it be better to avoid regex?
String liveprice = "$123,456.78";

do like this
NumberFormat format = NumberFormat.getCurrencyInstance();
Number number = format.parse("\$123,456.78");
System.out.println(number.toString());
output
123456.78

Try,
String liveprice = "$123,456.78";
String newStr = liveprice.replaceAll("[$,]", "");
replaceAll uses regex, to avoid regex than try with consecutive replace method.
String liveprice = "$1,23,456.78";
String newStr = liveprice.replace("$", "").replace(",", "");

Without regex, you can try this:
String output = "$123,456.78".replace("$", "").replace(",", "");

Here is more information Oracle JavaDocs:
liveprice = liveprice.replace("X", "");

Just use Replace instead
String liveprice = "$123,456.78";
String output = liveprice.replace("$", "");
output = output .replace(",", "");

Will this works?
String liveprice = "$123,456.78";
String newStr = liveprice.replace("$", "").replace(",","");
Output: 123456.78
Live Demo
Better One:
String liveprice = "$123,456.78";
String newStr = liveprice.replaceAll("[$,]", "")
Live Demo

In my case, #Prabhakaran's answer did not work, someone can try this.
String salary = employee.getEmpSalary().replaceAll("[^\\d.]", "");
Float empSalary = Float.parseFloat(salary);

Is a replace really what you need?
public void test() {
String s = "$123,456.78";
StringBuilder t = new StringBuilder();
for ( int i = 0; i < s.length(); i++ ) {
char ch = s.charAt(i);
if ( Character.isDigit(ch)) {
t.append(ch);
}
}
}
This will work for any decorated number.

Example using Swedish Krona currency
String x="19.823.567,10 kr";
x=x.replace(".","");
x=x.replaceAll("\\s+","");
x=x.replace(",", ".");
x=x.replaceAll("[^0-9 , .]", "");
System.out.println(x);
Will give the output ->19823567.10(which can now be used for any computation)

import java.text.NumberFormat
def currencyAmount = 9876543.21 //Default is BigDecimal
def currencyFormatter = NumberFormat.getInstance( Locale.US )
assert currencyFormatter.format( currencyAmount ) == "9,876,543.21"
Don't need getCurrencyInstance() if currency is not required.

I think that you could use regex. For example:
"19.823.567,10 kr".replace(/\D/g, '')

Related

delete dynamic character from string

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

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("=", "");

Android Java - String .replaceAll to replace specific characters (regex)

I need to remove some specific "special" characters and replace them with empty string if they show up.
I am currently having a problem with the regex, probably with the Java escaping. I can't put them all together, it just doesn't work, I tried a lot! T_T
Currently I am doing it one by one which is kinda silly, but for now at least it works, like that :
public static String filterSpecialCharacters(String string) {
string = string.replaceAll("-", "");
string = string.replaceAll("\\[", "");
string = string.replaceAll("\\]", "");
string = string.replaceAll("\\^", "");
string = string.replaceAll("/", "");
string = string.replaceAll(",", "");
string = string.replaceAll("'", "");
string = string.replaceAll("\\*", "");
string = string.replaceAll(":", "");
string = string.replaceAll("\\.", "");
string = string.replaceAll("!", "");
string = string.replaceAll(">", "");
string = string.replaceAll("<", "");
string = string.replaceAll("~", "");
string = string.replaceAll("#", "");
string = string.replaceAll("#", "");
string = string.replaceAll("$", "");
string = string.replaceAll("%", "");
string = string.replaceAll("\\+", "");
string = string.replaceAll("=", "");
string = string.replaceAll("\\?", "");
string = string.replaceAll("|", "");
string = string.replaceAll("\"", "");
string = string.replaceAll("\\\\", "");
string = string.replaceAll("\\)", "");
string = string.replaceAll("\\(", "");
return string;
}
Those are all the character I need to remove:
- [ ] ^ / , ' * : . ! > < ~ # # $ % + = ? | " \ ) (
I am clearly missing something, I can't figure out how to put it all in one line. Help?
Your code does not work in fact because .replaceAll("$", "") replaces an end of string with empty string. To replace a literal $, you need to escape it. Same issue is with the pipe symbol removal.
All you need to do is to put the characters you need to replace into a character class and apply the + quantifier for better performance, like this:
string = string.replaceAll("[-\\[\\]^/,'*:.!><~##$%+=?|\"\\\\()]+", "");
Note that inside a character class, most "special regex metacharacters" lose their special status, you only have to escape [, ], \, a hyphen (if it is not at the start/end of the character class), and a ^ (if it is the first symbol in the "positive" character class).
DEMO:
String s = "-[]^/,'*:.!><~##$%+=?|\"\\()TEXT";
s = s.replaceAll("[-\\[\\]^/,'*:.!><~##$%+=?|\"\\\\()]+", "");
System.out.println(s); // => TEXT
Use these codes
String REGEX = "YOUR_REGEX";
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(yourString);
yourString = m.replaceAll("");
UPDATE :
Your REGEX looks something like
String REGEX = "-|\\[|\\]|\\^|\\/|,|'|\\*|\\:|\\.|!|>|<|\\~|#|#|\\$|%|\\+|=\\?|\\||\\\\|\\\\\\\\|\\)|\\(";
SAPMLE :
String yourString = "#My (name) -is #someth\ing"";
//Use Above codes
Log.d("yourString",yourString);
OUTPUT

NumberFormatException when parsing Hindi numbers

I have an android application and today I have got a crash report which contains this:
This exception trigger when the application tries to parse string number which is provided by the user.
It is obvious that problem is the application cannot parse Hindi numbers! So, how can I solve this?
Regex
Using regex would be better if you want to match any unicode digits.The regex would be \\p{N}+ and here's how to use it:
Matcher m=Pattern.compile("\\p{N}+").matcher(input);
if(m.find())
{
System.out.println(m.group());
}
Locale
To answer your question you should use NumberFormat as mentioned in docs. Specify a Locale for NumberFormat.
NumberFormat nf = NumberFormat.getInstance(new Locale("hi", "IN"));
nf.parse(input);
You can use Character.getNumericValue(char).
The good thing about this method is that it can do what you need.
But to work in valid you should implement in your application support for local.
NumberFormat format = NumberFormat.getInstance(new Locale("hin","IND"));
Number parse = format.parse("१");
System.out.println(parse);
Prints 1.
Try this. This will remove non numeric characters.
Pattern p = Pattern.compile("(\\d+)");
Matcher m = p.matcher(str); // str is input String
while(m.find()) {
System.out.println(m.group(1));
}
If you are dealing with double(with decimal places). you can try this
String text = "123.0114cc";
String numOnly = text.replaceAll("\\p{Alpha}","");
double numVal = Double.valueOf(numOnly);
System.out.println(numVal);
Use
BigDecimal bigDecimal = new BigDecimal(YOUR_VALUE);
before applying the regex, as the BigDecimal supports 12 integers, 12.35 decimal, and 12 $ currency, 12% percentage and its localized value.
You can use the following method which receives a string and converts every Indian digit inside it to Arabic.
public static String convertAllIndianToArabic(String str)
{
for(int i=0; i<str.length(); i++)
{
if(str.charAt(i)=='٠')
str = str.substring(0, i)+"0"+str.substring(i+1);
else if(str.charAt(i)=='١')
str = str.substring(0, i)+"1"+str.substring(i+1);
else if(str.charAt(i)=='٢')
str = str.substring(0, i)+"2"+str.substring(i+1);
else if(str.charAt(i)=='٣')
str = str.substring(0, i)+"3"+str.substring(i+1);
else if(str.charAt(i)=='٤')
str = str.substring(0, i)+"4"+str.substring(i+1);
else if(str.charAt(i)=='٥')
str = str.substring(0, i)+"5"+str.substring(i+1);
else if(str.charAt(i)=='٦')
str = str.substring(0, i)+"6"+str.substring(i+1);
else if(str.charAt(i)=='٧')
str = str.substring(0, i)+"7"+str.substring(i+1);
else if(str.charAt(i)=='٨')
str = str.substring(0, i)+"8"+str.substring(i+1);
else if(str.charAt(i)=='٩')
str = str.substring(0, i)+"9"+str.substring(i+1);
}
return str;
}

Remove first word from a string in Java

What's the best way to remove the first word from a string in Java?
If I have
String originalString = "This is a string";
I want to remove the first word from it and in effect form two strings -
removedWord = "This"
originalString = "is a string;
Simple.
String o = "This is a string";
System.out.println(Arrays.toString(o.split(" ", 2)));
Output :
[This, is a string]
EDIT:
In line 2 below the values are stored in the arr array. Access them like normal arrays.
String o = "This is a string";
String [] arr = o.split(" ", 2);
arr[0] // This
arr[1] // is a string
You can use substring
removedWord = originalString.substring(0,originalString.indexOf(' '));
originalString = originalString.substring(originalString.indexOf(' ')+1);
This will definitely a good solution
String originalString = "This is a string";
originalString =originalString.replaceFirst("This ", "");
Try this using an index var, I think it's quite efficient :
int spaceIdx = originalString.indexOf(" ");
String removedWord = originalString.substring(0,spaceIdx);
originalString = originalString.substring(spaceIdx);
Prior to JDK 1.7 using below method might be more efficient, especially if you are using long string (see this article).
originalString = new String(originalString.substring(spaceIdx));
For an immediate answer you can use this :
removeWord = originalString.substring(0,originalString.indexOf(' '));
originalString = originalString.substring(originalString.indexOf(' '));
You can check where is the first space character and seperate string.
String full = "Sample Text";
String cut;
int pointToCut = full.indexOf( ' ');
if ( offset > -1)
{
cut = full.substring( space + 1);
}
String str = "This is a string";
String str2=str.substring(str.indexOf(" "));
String str3=str.replaceFirst(str2, "");
String's replaceFirst and substring
also you can use this solution:
static String substringer(String inputString, String remove) {
if (inputString.substring(0, remove.length()).equalsIgnoreCase(remove)) {
return inputString.substring(remove.length()).trim();
}
else {
return inputString.trim();
}
}
Example :
substringer("This is a string", "This");
You can use the StringTokenizer class.

Categories

Resources