How To Create Phone Number Format XXX-XXX-XXXX In Android - java

Can anybody help me to solve this problem ?
I want "-" between phone numbers.
I tried . It shows XXX-XXX-XXX-X Formats only . But i want XXX-XXX-XXXX Format .
Here Below I have mentioned my code.
Declare This under Oncreate
TextView TxtDocPhone=(TextView)findViewById(R.id.TxtDocPhone);
String numbersOnly = keepNumbersOnly(Phone);
String ProviderPhone = formatNumbersAsCode(numbersOnly);
Then call it
private String keepNumbersOnly(CharSequence s) {
return s.toString().replaceAll("[^0-9]", "");
}
private String formatNumbersAsCode(CharSequence s) {
int groupDigits = 0;
String tmp = "";
for (int i = 0; i < s.length(); ++i) {
tmp += s.charAt(i);
++groupDigits;
if (groupDigits == 3) {
tmp += "-";
// tmp += "";
groupDigits = 0;
}
}
return tmp;
}
Please guide me the correct way to achieve my objective.

Try this way,hope this will help you to solve your problem.
String formattedNumber = PhoneNumberUtils.formatNumber(unformattedNumber);
Take a look at PhoneNumberUtils for more options.

Finally i solve this issue . Just add below this in formatNumbersAsCode function .
return String.format("%s-%s-%s",s.subSequence(0,3),s.subSequence(3,6),s.subSequence(6,10));

You can try:
private String formatNumbersAsCode(CharSequence s) {
return String.format("%s-%s-%s",s.substring(0,3),s.substring(3,6),s.substring(6));
}

You best way to go is to use Regular Expressions.
You know your phone number should have the format XXX-XXX-XXXX, so you just write an appropriate RegEx for this, and you are fine!

Format with a space (" ") and then make a replaceall to the "-" character.

Related

Why doesn't Integer.parseInt work on a substring?

This conversion is not working, I am getting an exception,
not sure why
String str = "Draw: 1";
int draw = 0;
String temp;
temp = str.substring(5,7);
draw= Integer.parseInt(temp);
System.out.println(draw);
Because you're trying to parse " 1", notice the space. Adding a trim() should solve it.
temp = str.substring(5,7).trim();

String Manipulation in java 1.6

String can be like below. Using java1.6
String example = "<number>;<name-value>;<name-value>";
String abc = "+17005554141;qwq=1234;ddd=ewew;otg=383";
String abc = "+17005554141;qwq=123454";
String abc = "+17005554141";
I want to remove qwq=1234 if present from String. qwq is fixed and its value can VARY like for ex 1234 or 12345 etc
expected result :
String abc = "+17005554141;ddd=ewew;otg=383";
String abc = "+17005554141"; \\removed ;qwq=123454
String abc = "+17005554141";
I tried through
abc = abc.replaceAll(";qwq=.*;", "");
but not working.
I came up with this qwq=\d*\;? and it works. It matches for 0 or more decimals after qwq=. It also has an optional parameter ; since your example seems to include that this is not always appended after the number.
I know the question is not about javascript, but here's an example where you can see the regex working:
const regex = /qwq=\d*\;?/g;
var items = ["+17005554141;qwq=123454",
"+17005554141",
"+17005554141;qwq=1234;ddd=ewew;otg=383"];
for(let i = 0; i < items.length; i++) {
console.log("Item before replace: " + items[i]);
console.log("Item after replace: " + items[i].replace(regex, "") + "\n\n");
}
You can use regex for removing that kind of string like this. Use this code,
String example = "+17005554141;qwq=1234;ddd=ewew;otg=383";
System.out.println("Before: " + example);
System.out.println("After: " + example.replaceAll("qwq=\\d+;?", ""));
This gives following output,
Before: +17005554141;qwq=1234;ddd=ewew;otg=383
After: +17005554141;ddd=ewew;otg=383
.* applies to multi-characters, not limited to digits. Use something that applies only to bunch of digits
abc.replaceAll(";qwq=\\d+", "")
^^
Any Number
please try
abc = abc.replaceAll("qwq=[0-9]*;", "");
If you don't care about too much convenience, you can achieve this by just plain simple String operations (indexOf, replace and substring). This is maybe the most legacy way to do this:
private static String replaceQWQ(String target)
{
if (target.indexOf("qwq=") != -1) {
if (target.indexOf(';', target.indexOf("qwq=")) != -1) {
String replace =
target.substring(target.indexOf("qwq="), target.indexOf(';', target.indexOf("qwq=")) + 1);
target = target.replace(replace, "");
} else {
target = target.substring(0, target.indexOf("qwq=") - 1);
}
}
return target;
}
Small test:
String abc = "+17005554141;qwq=1234;ddd=ewew;otg=383";
String def = "+17005554141;qwq=1234";
System.out.println(replaceQWQ(abc));
System.out.println(replaceQWQ(def));
outputs:
+17005554141;ddd=ewew;otg=383
+17005554141
Another one:
abc.replaceAll(";qwq=[^;]*;", ";");
You must to use groups in replaceAll method.
Here is an example:
abc.replaceAll("(.*;)(qwq=\\d*;)(.*)", "$1$3");
More about groups you can find on: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html

Remove all characters except last n characters from a string

i am trying to remove all text except last 10 characters but getting error in android
09-15 16:22:58.146: E/AndroidRuntime(13630): java.lang.StringIndexOutOfBoundsException: length=228; index=263
but it is working on java when i tried it in separate class.
here is what i tried? can anybody tell me if there is any issue regarding substring in android?
String allchar =
"PJGOGROG fnkmslkjsfsdmnsgdnklnsgklsgknlgrf jkghijgdlkjkgjdfkjgf kjlgdfkjlfdgfjklklj
kljfdkjlfkjldfdkjslkljdfskjlfsjkldfsjklkljs
fdsjklsdfkljsfdkljkhgfhhgdfsgkhdfskghfdskghfdsghsfdghafevbhfsvgydcgubcdmgycdgfehkhfeghjgh68
Alias12345";
String number = "";
String reqtext = allchar.replaceAll("\\s+","");
number = reqtext.substring(reqtext.length()-10 );
System.out.println(number);
Well if substring() doesn't work, you can try doing it manually:
String allchar =
"PJGOGROG fnkmslkjsfsdmnsgdnklnsgklsgknlgrf jkghijgdlkjkgjdfkjgf kjlgdfkjlfdgfjklklj
kljfdkjlfkjldfdkjslkljdfskjlfsjkldfsjklkljs
fdsjklsdfkljsfdkljkhgfhhgdfsgkhdfskghfdskghfdsghsfdghafevbhfsvgydcgubcdmgycdgfehkhfeghjgh68
Alias12345";
StringBuilder number = new StringBuilder();
String reqtext = allchar.replaceAll("\\s+","");
for(int i = reqtext.length()-10; i < reqtext.length(); i++)
{
number.append(reqtext.charAt(i));
}
System.out.println(number.toString());
String allchar = "PJGOGROG fnkmslkjsfsdmnsgdnklnsgklsgknlgrf jkghijgdlkjkgjdfkjgf kjlgdfkjlfdgfjklkljkljfdkjlfkjldfdkjslkljdfskjlfsjkldfsjklkljsfdsjklsdfkljsfdkljkhgfhhgdfsgkhdfskghfdskghfdsghsfdghafevbhfsvgydcgubcdmgycdgfehkhfeghjgh68Alias12345";
String number = "";
String reqtext = allchar.replaceAll("\\s+","");
number = reqtext.substring(reqtext.length()-10, reqtext.length());
System.out.println(number);
This code works fine for me in android.
Avoid declaring so many variable, try using :
number = allchar.substring(allchar.length()-10, allchar.length());

How to print newline when it find \n in a string variable value?

Good Morning,
I had a string value like
Name:Anilbabu\nPlace:Pamarru\nAge::22\n
while printing that string variable.. I don't want to see "\n" in output, Instead, I want to have new line printed like,
Name:Anilbabu
Place:Pamarru
Age:22
Please help me friends, Please give solution in Java.
Thank you.
Use StringTokenizer
StringTokenizer strings = new StringTokenizer(input, "\\n");
while (strings.hasMoreTokens()){
System.out.println(strings.nextToken());
}
OR
use :
System.out.print(input.replace("\\n", "\n"));
Like this
String str = "Name:Anilbabu\nPlace:Pamarru\nAge::22\n"; // the String.
System.out.print(str); // Print the String
Outputs
Name:Anilbabu
Place:Pamarru
Age:22
do like this
String input = "Name:Anilbabu\nPlace:Pamarru\nAge::22\n";
String[] result = input.split("[\\n]");
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
Output
Name:Anilbabu
Place:Pamarru
Age::22
Just print the value
System.out.println("Name:Anilbabu\nPlace:Pamarru\nAge::22\n");
or Assign it to a variable and then print
String st ="Name:Anilbabu\nPlace:Pamarru\nAge::22\n";
System.out.println(st);

How can you parse the string which has a text qualifier

How can I parse a String str = "abc, \"def,ghi\"";
such that I get the output as
String[] strs = {"abc", "\"def,ghi\""}
i.e. an array of length 2.
Should I use regular expression or Is there any method in java api or anyother opensource
project which let me do this?
Edited
To give context about the problem, I am reading a text file which has a list of records one on each line. Each record has list of fields separated by delimiter(comma or semi-colon). Now I have a requirement where I have to support text qualifier some thing excel or open office supports. Suppose I have record
abc, "def,ghi"
In this , is my delimiter and " is my text qualifier such that when I parse this string I should get two fields abc and def,ghi not {abc,def,ghi}
Hope this clears my requirement.
Thanks
Shekhar
The basic algorithm is not too complicated:
public static List<String> customSplit(String input) {
List<String> elements = new ArrayList<String>();
StringBuilder elementBuilder = new StringBuilder();
boolean isQuoted = false;
for (char c : input.toCharArray()) {
if (c == '\"') {
isQuoted = !isQuoted;
// continue; // changed according to the OP comment - \" shall not be skipped
}
if (c == ',' && !isQuoted) {
elements.add(elementBuilder.toString().trim());
elementBuilder = new StringBuilder();
continue;
}
elementBuilder.append(c);
}
elements.add(elementBuilder.toString().trim());
return elements;
}
This question seems appropriate: Split a string ignoring quoted sections
Along that line, http://opencsv.sourceforge.net/ seems appropriate.
Try this -
String str = "abc, \"def,ghi\"";
String regex = "([,]) | (^[\"\\w*,\\w*\"])";
for(String s : str.split(regex)){
System.out.println(s);
}
Try:
List<String> res = new LinkedList<String>();
String[] chunks = str.split("\\\"");
if (chunks.length % 2 == 0) {
// Mismatched escaped quotes!
}
for (int i = 0; i < chunks.length; i++) {
if (i % 2 == 1) {
res.addAll(Array.asList(chunks[i].split(",")));
} else {
res.add(chunks[i]);
}
}
This will only split up the portions that are not between escaped quotes.
Call trim() if you want to get rid of the whitespace.

Categories