+6 votes
10.5k views
in Programming by Expert (6.4k points)

I want to know how I can remove comma or another characters from a string, like 

I have string1 which is Rs. 30,000 and strng2 which is 30000 and these strings values are coming dynamically.

Now I have to compare them and using this code

string1 which is Rs. 30,000 and strng2 which is 30000

 

if(string1.contains(string2)){

Sysyem.out.println("true");

}

but because of "Rs." and "," result is not coming true, Can you help me how can I remove Rs. and comma from the strings?

Thanks For help!

closed

2 Answers

+2 votes
by
selected by
 
Best answer
class Removal
{
public static void main(String args[])
{
String str1=new String("Rs. 30,000");
String str2=new String("30000");
String string1="";
//lets us first remove irrelevant data from str1
int ch;    // This is used to typecast the character to integer value(ASCII value of a character). 
for(int i=0;i<str1.length();i++)
{
ch=(int)str1.charAt(i);
if(ch<=57 && ch>=48)   // 0 is represented as 48    and    9 is represented as 57 in ASCII
{
string1=string1+str1.charAt(i);   // concatenation of number
}
}
 
// our final aim to compare 
if(string1.equals(str2))
System.out.println("True");
else
System.out.println("False");
}
}
0
by Expert (6.4k points)
Thanks @Tiger98 :)
+1 vote
by Expert (3.8k points)

This is another way to remove comma or other part of string:

you have  String str1=new String("Rs. 30,000");

              String str2=new String("30000");
              str1= str1.replace(",", "");
              str1= str1.replace("Rs.", "");
So now if you compare them so result will be true.

                  if(string1.equals(string2)){

                   Sysyem.out.println("true");

                   }

I hope you like it !

0
by Expert (6.4k points)
Thanks @jatin but in this case if another new character comes again in string so i need to change in code So i think Answer given by @Tiger98 above will be fit for this situation, i appreciate your effort.

Not a Member yet?

Ask to Folks Login

My Account

Your feedback is highly appreciated