I have problem with finding phone number in string.
I have function:
public void getPhoneNumber()
{
Pattern intsOnly = Pattern.compile("\\d+");
Matcher makeMatch = intsOnly.matcher(number);
makeMatch.find();
String result = makeMatch.group();
Log.i("Pattern", result);
}
But I have bad result.
My string:
String number = "String string s. s. str. 23-232 12 23 adsdsa"
Is your number always in the format 23-232 12 23?. If so you can try the below.
Try the below
String s="String string s. s. str. 23-232 12 23 adsdsa";
Pattern p = Pattern.compile("[0-9]{2}[-][0-9]{3}[ ][0-9]{2}[ ][0-9]{2} ");
// match 2 numbers followed by -,
// match 3 numbers followed by space.
// match 2 numbers followed by space.
// match 2 numbers followed by space.
Matcher m = p.matcher(s);
if(m.find()) {
System.out.println("............"+m.group(0));
}
Edit:
Pattern p = Pattern.compile("(\\([0-9]{2}\\)|[0-9]{2})[ ][0-9]{3}[ ][0-9]{2,2}[ ][0-9]{2} ");
Use a or operator match (23) or 23
You can also remove the rounded brackets by using the replace method
String s="String string s. s. str. (23) 232 32 34 11111adsds0000000000000000a0";
String r = s.replace("(","");
String r2= r.replace(")", "");
System.out.println(r2);
//String string s. s. str. 23 232 32 34 11111adsds0000000000000000a0
Try using regex, similiar question here: Link
String value = string.replaceAll("[^0-9]","");
I wrote this:
This solved my problem :)
public String getPhoneNumber()
{
char[] temp = numer.toCharArray();
String value="";
int licz=0;
for(int i=0;i<temp.length;i++)
{
if(licz<9)
{
if(Character.toString(temp[i]).matches("[0-9]"))
{
value+=Character.toString(temp[i]);
licznik++;
}
else if(Character.toString(temp[i]).matches("\u0020|\\-|\\(|\\)"))
{
}
else
{
value="";
licz=0;
}
}
}
if(value.length()!=9)
{
value=null;
}
else
{
value="tel:"+value.trim();
}
return value;
}
Related
I want to comapare two textbox values words by words and check if the words are same or not. If its not same then it should tell me the percentage of matching words.
For example : I am a good boy(text box1)
Am a god boy (text box 2)
Then the result should be (3/5)*100 as 2 words are not matching that is I and good.
Please tell me how to do this.
here is a code as you want
public class Test {
public static void main(String[] args) {
String str1 = "I am a good boy";
String [] s_str1 = str1.split(" ");
String str2 = "Am a god boy";
String [] s_str2 = str2.split(" ");
int match = 0;
for(int i=0;i<s_str1.length;i++){
for(int j=0;j<s_str2.length;j++){
if(s_str1[i].equalsIgnoreCase(s_str2[j])){
match++;
}
}
}
int result = match*100/s_str1.length; //use length of string which is
your main str
System.out.println(result);
}
}
Try this:
int getCommonWords(String s1, String s2) {
Set<String> set1 = new HashSet<>(Arrays.asList(s1.split(" ")));
Set<String> set2 = new HashSet<>(Arrays.asList(s2.split(" ")));
set1.retainAll(set2);
return set1.size();
}
returns the number of common words between 2 strings. It is case-sensitive.
I have a method that converts numeric values to a formatted string. It works well, but only on versions less than android 7. On Android 7 and above it is ignored.
public static String printableSumSeparators(double sum, String format) {
DecimalFormatSymbols dfSymbols = new DecimalFormatSymbols();
dfSymbols.setDecimalSeparator(COMMA_SEPARATOR);
dfSymbols.setGroupingSeparator(' ');
DecimalFormat df = new DecimalFormat(format, dfSymbols);
df.setGroupingUsed(true);
return df.format(sum);
}
Where COMMA_SEPARATOR = ',';
The input of the method is fed with 2 parameters, the number itself for the conversion and the format in the form: ##.0#
Example:
Input: 500000
Output: 500 000
But on the android 7 it does not work and the number is not formatted
Question: How to fix this bug and make it work on the latest version of android
On the latest versions of android you also need to setGroupingSize. Like this:
DecimalFormatSymbols dfSymbols = new DecimalFormatSymbols();
dfSymbols.setDecimalSeparator(',');
dfSymbols.setGroupingSeparator(' ');
DecimalFormat df = new DecimalFormat(format, dfSymbols);
df.setGroupingSize(3);
df.setGroupingUsed(true);
Maybe below code is useful for you, because its work like separating the decimal value using comma's.
protected String getCommaSeparated(String s)
{
try
{
if (s.length() > 0)
{
s =
customFormat("##,##,##0",Double.parseDouble(s.toString().replace(",","")));
if(s.length() > 0)
{
return s;
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return s;
}
public String customFormat(String pattern, double value)
{
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
return output;
}
In my phonebook on my mobile I have all sorts of contacts like :
+(353) 085 123 45 67
00661234567
0871234567
(045)123456
I'm putting them all into E.164 format which I've largely completed but the question I need resolved is this:
How can I strip all characters (including spaces) except numbers in my string, apart from the first character if it is '+' or a number ?
string phoneNumberofContact;
So for example the cases above would look like :
+3530851234567
00661234567
0871234567
045123456
Update
To handle + only in the first position, you could do:
boolean starsWithPlus = input.charAt(0) == '+';
String sanitized = input.replaceAll("[^0-9]", "");
if (startsWithPlus) {
sanitized = "+" + sanitized;
}
So basically I'm checking to see if it starts with plus, then stripping out everything but digits, and then re-adding the plus if it was there.
Original
Assuming you only want to keep + or digits, a simple regex will work, and String provides the replaceAll() method to make it even easier.
String sanitized = input.replaceAll("[^+0-9]", "");
This method would do the trick
public String cleanPhoneDigits(String phonenum) {
StringBuilder builder = new StringBuilder();
if (phonenum.charAt(0).equals('+') {
builder.append('+');
}
for (int i = 1; i < phonenum.length(); i++) {
char c = phonenum.charAt(i);
if (Character.isDigit(c)) {
builder.append(c);
}
}
return builder.toString();
}
I want to split this string
String info = "0.542008835 meters height from ground";
from this i want to get only two decimals like this 0.54.
by using this i am getting that
String[] _new = rhs.split("(?<=\\G....)");
But i am facing problem here, if string does't contain any decimals like this string
String info = "1 meters height from ground";
for this string i am getting those characters upto first 4 in the split string like 1 me.
i want only numbers to split if it has decimals, How to solve this problem.
if(info.contains("."))
{
String[] _new = rhs.split("(?<=\\G....)");
}
I think you can check by white space after first value. see this
If you get the space then get first character only.
For checking if a string contains whitespace use a Matcher and call it's find method.
Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(s);
boolean found = matcher.find();
If you want to check if it only consists of whitespace then you can use String.matches:
boolean isWhitespace = s.matches("^\\s*$");
You could use a regex to do this as an alternative to Deepzz's method, this will handle the case where there is a '.' in the later part of the String, I've included an example below. It's not clear from your question is you actually want to remaining part of the String, but you could add a second group to the reg ex to capture this.
public static void main(String[] args) {
final String test1 = "1.23 foo";
final String test2 = "1 foo";
final String test3 = "1.234 foo";
final String test4 = "1.234 fo.o";
final String test5 = "1 fo.o";
getStartingDecimal(test1);
getStartingDecimal(test2);
getStartingDecimal(test3);
getStartingDecimal(test4);
getStartingDecimal(test5);
}
private static void getStartingDecimal(final String s) {
System.out.print(s + " : ");
Pattern pattern = Pattern.compile("^(\\d+\\.\\d\\d)");
Matcher matcher = pattern.matcher(s);
if(matcher.find()) {
System.out.println(matcher.group(1));
} else {
System.out.println("Doesn't start with decimal");
}
}
Assuming the number is always the first part of the string:
String numStr = rhs.split(" ")[0];
Double num = Double.parseDouble(numStr);
After that you can use the String Formatter to get the desired representation of the number.
This will work when you know the String near the numbers, with int and double numbers as well.
String a ="0.542008835 meters height from ground";
String b = a.replace(" meters height from ground", "");
int c = (int) ((Double.parseDouble(b))*100);
double d = ((double)c/100);
I want to split a string and get a word finally. My data in database is as follows.
Mohandas Karamchand Gandhi (1869-1948), also known as Mahatma Gandhi, was born in Porbandar in the present day state of Gujarat in India on October 2, 1869.
He was raised in a very conservative family that had affiliations with the ruling family of Kathiawad. He was educated in law at University College, London.
src="/Leaders/gandhi.png"
From the above paragraph I want get the image name "gandhi". I am getting the index of "src=". But now how can I get the image name i.e "gandhi" finally.
My Code:
int index1;
public static String htmldata = "src=";
if(paragraph.contains("src="))
{
index1 = paragraph.indexOf(htmldata);
System.out.println("index1 val"+index1);
}
else
System.out.println("not found");
You can use the StringTokenizer class (from java.util package ):
StringTokenizer tokens = new StringTokenizer(CurrentString, ":");
String first = tokens.nextToken();// this will contain one word
String second = tokens.nextToken();// this will contain rhe other words
// in the case above I assumed the string has always that syntax (foo: bar)
// but you may want to check if there are tokens or not using the hasMoreTokens method
Try this code. Check if it working for you..
public String getString(String input)
{
Pattern pt = Pattern.compile("src=.*/(.*)\\..*");
Matcher mt = pt.matcher(input);
if(mt.find())
{
return mt.group(1);
}
return null;
}
Update:
Change for multiple item -
public ArrayList<String> getString(String input)
{
ArrayList<String> ret = new ArrayList<String>();
Pattern pt = Pattern.compile("src=.*/(.*)\\..*");
Matcher mt = pt.matcher(input);
while(mt.find())
{
ret.add(mt.group(1));
}
return ret;
}
Now you'll get an arraylist with all the name. If there is no name then you'll get an empty arraylist (size 0). Always make a check for size.