Hey there! any question in your mind? Ask It Now!.

Popular Categories





How to remove comma or unwanted characters from a string?

+6 votes
2,240 views
asked in Programming by krish Expert (6,310 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!

2 Answers

+2 votes
answered by Tiger98
selected by krish
 
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");
}
}
commented by krish Expert (6,310 points)
Thanks @Tiger98 :)
+1 vote
answered by jatin Expert (3,823 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 !

commented by krish Expert (6,310 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.

Related Questions

+2 votes
2 answers 788 views
+3 votes
1 answer 643 views
+2 votes
1 answer 141 views
+1 vote
1 answer 776 views
–1 vote
0 answers 111 views
+2 votes
1 answer 504 views
0 votes
1 answer 149 views
+4 votes
5 answers 713 views
+1 vote
1 answer 145 views
+6 votes
1 answer 45 views

Not a Member yet?

Ask to Folks Login

My Account
1067 Folks are online
69 members and 998 guest online
Your feedback is highly appreciated