How to construct a Currency Locale from a String? - java

How does one get a Locale from a String containing both characters and numberals? Is it even possible? I'm not terribly advanced in java, and I'm afraid this is getting into the deeper end of the figurative pool.
Say I have;
String userInput = "250.00 SEK";
From this I want to device the means to print "Sweden".
So all I know is the currency code, and I'm wanting the DisplayName for that locale.

Assuming all currencies have 3 characters (http://www.xe.com/iso4217.php) you could just
String code = userInput.substring(userInput.length()-3,userInput.length());
state = Currency.valueOf(code);
system.out.print(state.name);
public enum Currency{
SEK("Sweden"),
GBP("British Pound");
private String name;
public Currency(String n) { this.name = n; }
public String toString() { return this.name; }
}

I think your only hope is to build a Map<String, Locale> by hand and do lookups based on the country code at the end of your currency string. There is no automated way to go from a currency to a locale (at least that I am aware of)

You could use the Currency class in combination with the codes used in ISO 4217

String userInput = "250.00 SEK";
final Set<Currency> availableCurrencies = Currency.getAvailableCurrencies();
for (Currency availableCurrency : availableCurrencies) {
final String currencyCode = availableCurrency.getCurrencyCode();
final String displayName = availableCurrency.getDisplayName();
if (userInput.contains(currencyCode)){
System.out.println("Currency is " + availableCurrency.getDisplayName());
}
}
Currency is Swedish Krona

Assuming that your string will always have space in it you can split it by space and then get currency instance by the second value in the returned array.
String userInput = "250.00 SEK";
String[] parts = userInput.split(" ");
Currency currency = Currency.getInstance(parts[1]);
System.out.print(currency.getDisplayName());

String userInput = "250.00 SEK";
final Set<Currency> availableCurrencies = Currency.getAvailableCurrencies();
for (Currency availableCurrency : availableCurrencies) {
final String strCode = availableCurrency.getCurrencyCode();
final String currencyCode = strCode;
if (userInput.contains(currencyCode)){
for (Locale locale : NumberFormat.getAvailableLocales()) {
String code = NumberFormat.getCurrencyInstance(locale).getCurrency().getCurrencyCode();
if (strCode.equals(code)) {
System.out.println(locale.getDisplayCountry());;
}
}
}
}
Will give you: Sweden

Related

How to remove String value from a String at First Character in java?

I want to remove countrycode which contains +91 from mobileNumber at first three characters only.
String countrycode = +91;
String mobileNumber = 123917890;
if (mobileNumber.contains(countrycode)){
int v = countrycode.length();
String phonenumber = mobileNumber.substring(v);
System.out.println(phonenumber);
} else {
System.out.println("mobile number doesn't have country code");
}
But in mycode it removing 91 from mobileNumber if it's contains in whole String.
getting output:
3917890
But I want to remove countrycode at first String three characters if contains. How should I create that type of condition?
You can use String replace to replace the +91 with blank if found
String countrycode = +91;
String mobileNumber = 123917890;
String noCountryCode = mobileNumber.replace("+91", "");
System.out.println(noCountryCode);
I got my answer, thankyou to all for helping me
just simple
String countrycode = +91;
String mobileNumber = 123917890;
if (mobileNumber.contains("+" + countrycode)){
int v = countrycode.length();
String phonenumber = num_code.substring(v);
System.out.println(phonenumber);
} else {
System.out.println("mobile number doesn't have country code");
}
now it's working as expected result.

Java string problem: replacing specific part of a string

A method replacement replaces all names (from given String a) in [Name] or {Name} brackets, with telephone numbers if [] these brackets, or e-mails if {} these brackets. The address book is represented with array tel, whose elements can be "Tel Name telephoneNumber" or "Mail Name mail". For example if input is: "You can contact jake via phone number [Jake] or via email {Jake}", output should be "You can contact jake via phone number +12345 or via email jake#gmail.com", and tel elements are "Tel Jake +12345" and "Mail Jake jake#gmail.com". If the given name does not exist in address book do nothing with the string. The problem that I have is when it comes to replacing substrings I use method replaceFirst which will replace the first occurrence of the substring that I want to replace.
Maybe the shorter question would be how to replace specific part of string?
public static String replacement(String a, String[] tel) {
for (int i = 0; i<a.length()-1; i++) {
char c = a.charAt(i);
if (c=='[') {
int ind = a.indexOf(']', i);
String name = a.substring(i+1, ind);
for (int j=0; j<tel.length; j++) {
int ind1 = tel[j].indexOf(' ', 4);
String name1 = tel[j].substring(4, ind1);
String p = tel[j].substring(0,3);
String help = "Tel";
int temp = p.compareTo(help);
if (ime.equals(ime1)==true && temp==0) {
String telephone = tel[j].substring(ind1+1, tel[j].length());
a = a.replaceFirst(name, telephone);
}
}
}
if (c=='{') {
int ind = a.indexOf('}', i);
String name = a.substring(i+1, ind);
for (int j=0; j<tel.length; j++) {
int ind1 = tel[j].indexOf(' ', 5);
String name1 = tel[j].substring(5, ind1);
String p = tel[j].substring(0,4);
if (name.equals(name1) && p.compareTo("Mail")==0) {
String mail = tel[j].substring(ind1+1, tel[j].length());
a = a.replaceFirst(name, mail);
}
}
}
}
return a;
}
Main:
String a = "In NY you can contact peter via telephone number [Peter] or e-mail {Peter}. In London you can contact anna via telephone number [Anna] or e-mail {Anna}."
+ "In Chicago you can contact shawn via telephone number [Shawn] or e-mail {Shawn}";
String [] tel = {"Mail Peter peter#gmail.com", "Tel Anna +3456","Tel Shawn +1234", "Mail Shawn shawn#yahoo.com"};
String t = replacement(a,tel);
System.out.println(t);
Console:
In NY you can contact peter via telephone number [peter#gmail.com] or e-mail {peter#gmail.com}.
In London you can contact anna via telephone number [+3456] or e-mail {Anna}.In Chicago you can
contact shawn via telephone number [+1234] or e-mail {shawn#yahoo.com}
Instead of encoding the type of the data (email vs phone number) and the replacement key into strings, I would put the data into separate variables and ues data structures like Map:
Map<String, String> tel = Map.of("Anna", "+3456", "Shawn", "+1234");
Map<String, String> mail = Map.of("Peter", "peter#gmail.com", "Shawn", "shawn#yahoo.com");
String t = replacement(a, tel, mail);
The replacement function could use a regular expression to find the substrings that match the key words you want to replace [something] and {something}. It would check which one it found, and add a replacement using the telephone or email it finds in the map data structure.
private static String replacement(String a, Map<String, String> tel, Map<String, String> mail) {
Pattern compile = Pattern.compile("\\{(.*?)\\}|\\[(.*?)\\]");
Matcher matcher = compile.matcher(a);
StringBuilder sb = new StringBuilder();
// Find substrings matching {something} and [something]
while (matcher.find()) {
String matched = matcher.group(0);
// Which was it, { or [ ?
if (matched.charAt(0) == '{') {
// Email. Replace from "mail"
String emailAddress = mail.getOrDefault(matcher.group(1), matched);
matcher.appendReplacement(sb, emailAddress);
} else if (matched.charAt(0) == '[') {
// Telephone. Replace from "tel"
String phoneNumber = tel.getOrDefault(matcher.group(2), matched);
matcher.appendReplacement(sb, phoneNumber);
}
}
matcher.appendTail(sb);
return sb.toString();
}
Handling of strings in a specified format is done best using regular expressions. You define a specified pattern and after you find a part matching your pattern, you can replace it or analyze further.
It's best to write your code to make it easily extensible. For example - if a new contact form is added (home address, fax, business phone number), it should be easy to handle it in the code. Your solution makes it harder to resolve such problems as a whole new if branch is required and it's easy to make a mistake, it also makes the code less readable.
When dealing with a kind of dictionary (like your input String array), it's worth using a Map as it makes the processing faster and the code more readable. When a constant values are present, it's worth to define them too - as constants or enum values. Also - Java allows for writing more functional and more readable, functional-style code instead of nested for-eaches - it's worth using those features (JDK8+).
Please, find the code snippet below and a whole project with tests comparing your solution to mine on GitHub - you can view it there or clone the repository and verify the code yourself:
// we can simply add new contact types and their matchers using the constant below
private static final Map<Pattern, ContactType> CONTACT_PATTERNS = Map.of(
Pattern.compile("\\[(\\S+)]"), ContactType.TEL,
Pattern.compile("\\{(\\S+)}"), ContactType.MAIL
);
#Override
public String replace(String input, String[] dictionary) {
// we're mapping the dictionary to make it easier to use and more readable (also in debugging)
Map<ContactType, Map<String, String>> contactTypeToNameToValue =
Arrays.stream(dictionary)
.map(entry -> entry.split(" ")) // dictionary entry is split by ' ' character
.collect(groupingBy(entry -> ContactType.fromString(entry[0]), // first split part is the contact type
toMap(entry -> entry[1], // second part is the person's name
entry -> entry[2]))); // third part is the contact value
String output = input;
for (Map.Entry<Pattern, ContactType> entry : CONTACT_PATTERNS.entrySet()) {
Pattern pattern = entry.getKey();
ContactType contactType = entry.getValue();
output = pattern.matcher(output)
.replaceAll(matchResult -> {
String name = matchResult.group(1);
// we search our dictionary and get value from it or get the original value if nothing matches given name
return Optional.ofNullable(contactTypeToNameToValue.get(contactType))
.map(nameToValue -> nameToValue.get(name))
.orElseGet(matchResult::group);
});
}
return output;
}
public enum ContactType {
TEL,
MAIL;
private static ContactType fromString(String value) {
return Arrays.stream(values())
.filter(enumValue -> enumValue.name().equalsIgnoreCase(value))
.findFirst()
.orElseThrow(RuntimeException::new);
}
}

Java - how to extract multiple things from a string and store in an object

public class Main{
public static void main(String[] args)
{
String a = "PORT:AXN,0,10;BGT,20,30;CXZ,10,30|BENCH:AXN,50,10;BGT,30,30;DFG,30,20;XYZ,0,10";
Port port = new Port();
Port bench = new Port();
}
}
public class Port{
List<String> name = new ArrayList<String>();
List<Integer> qty = new ArrayList<Integer>();
List<Integer> price = new ArrayList<Integer>();
}
I want to go through the string and store the information in these objects so
port object gets:
AXN,BGT,CXZ in the name list
0,20,10 in the qty list
10,30,30 in the price list
And similarly for the bench object using the bench data in the string.
In the string, there can be any number of tuples in the string for each. eg. port can have 5 sets, bench can have 8. And the codes for each (the name) have to be 3 alpha characters long but can be anything.
How can I go about doing this? The only thing I can think of is using the split method somehow but am having a hard time working out exactly how to use it? Any help would be great! thanks
You can use split with some loops like this :
String a ="PORT:AXN,0,10;BGT,20,30;CXZ,10,30|BENCH:AXN,50,10;BGT,30,30;DFG,30,20;XYZ,0,10";
Port port = new Port();
String[] tuples = a.split("\\|");
//Split with | to get the tuples
//PORT:AXN,0,10;BGT,20,30;CXZ,10,30
//BENCH:AXN,50,10;BGT,30,30;DFG,30,20;XYZ,0,10
for(String tuple : tuples){
String[] objects = tuple.split(";");//split each tuple with ; to get the information
//PORT:AXN,0,10
//BGT,20,30
//CXZ,10,30
for(String obj : objects){
//split with , to get the three properties(name, qty, price)
String[] spl = obj.replaceAll("(.*?):(.*?)", "$2").split(",");
port.name.add(spl[0]);//name value
port.qty.add(Integer.parseInt(spl[1]));//qty value
port.price.add(Integer.parseInt(spl[2]));//price value
}
}
Classes
As I suggested, I think modifying a bit your Port class and creating a PortObject class could improve readibility. Basically:
A port has a name and a list of port objects
A port object has a name, a quantity and a price:
For each class, I'll create two constructor:
constructor which takes all attributes and assign
constructor which build object from a raw String input
Classes are private static and don't have getter because I put everything in the Main.java but this is not a good practice!
Port class
private static class Port {
final String name;
final List<PortObject> portObjects;
// format is PORT:AXN,0,10;BGT,20,30;CXZ,10,30
public Port(String input) {
String[] split = input.split(":");
name = split[0];
this.portObjects = Pattern.compile(";").splitAsStream(split[1])
.map(PortObject::new)
.collect(Collectors.toList());
}
public Port(String name, List<PortObject> portObjects) {
this.name = name;
this.portObjects = portObjects;
}
#Override
public String toString() {
return "Port:" + name + " " + portObjects.toString();
}
}
Port object class
private static class PortObject {
final String name;
final int qty;
final int price;
// format is AXN,0,10
public PortObject(String input) {
String[] split = input.split(",");
name = split[0];
qty = Integer.parseInt(split[1]);
price = Integer.parseInt(split[2]);
}
public PortObject(String name, int qty, int price) {
this.name = name;
this.qty = qty;
this.price = price;
}
#Override
public String toString() {
return name + ":" + qty + ":" + price;
}
}
Not a so good idea: Regex
When it's about matching a pattern, one may think about Regex. Regex will require the second constructor (the one which does not take a raw String input as argument). I'm not a Regex expert so I'll do a simple way:
[^\\|]+ is the equivalent of String.split("\\|")
(\\w+):(.*) will match the port name and the list of port objects. This list will be processed by the next regex:
(\\w{3}),(\\d+),(\\d+);? will match the three-characters port object name, ask for a digit-only quantity and a digit-only price followed by an optional semi-colon (optional because the last port object does not have semi-colon)
Put in code, it looks like as follow:
public static void main(String[] args) throws IOException {
// the input
String a = "PORT:AXN,0,10;BGT,20,30;CXZ,10,30|BENCH:AXN,50,10;BGT,30,30;DFG,30,20;XYZ,0,10";
// Option 1: Regex
List<Port> portList1 = new ArrayList<>();
// initialise regex
String splitRegex = "[^\\|]+"; // Regex 1.
String portRegex = "(\\w+):(.*)"; // Regex 2.
String portObjectRegex = "(\\w{3}),(\\d+),(\\d+);?"; // Regex 3.
Pattern patternSplit = Pattern.compile(splitRegex);
Pattern patternPort = Pattern.compile(portRegex);
Pattern patternPortObject = Pattern.compile(portObjectRegex);
Matcher matcherSplit = patternSplit.matcher(a);
Matcher matcherPort;
Matcher matcherPortObject;
// look for each port
while (matcherSplit.find()) {
String portSplit = matcherSplit.group();
matcherPort = patternPort.matcher(portSplit);
while (matcherPort.find()) {
// keep the port name
String name = matcherPort.group(1);
List<PortObject> portObjectList = new ArrayList<>();
matcherPortObject = patternPortObject.matcher(matcherPort.group(2));
// look for each port object
while (matcherPortObject.find()) {
String poName = matcherPortObject.group(1);
int poQty = Integer.parseInt(matcherPortObject.group(2));
int poPrice = Integer.parseInt(matcherPortObject.group(3));
portObjectList.add(new PortObject(poName, poQty, poPrice));
}
portList1.add(new Port(name, portObjectList));
}
}
// Print
System.out.println("PortList1:\n" + portList1 + "\n");
}
The output is
PortList1:
[Port:PORT [AXN:0:10, BGT:20:30, CXZ:10:30], Port:BENCH [AXN:50:10, BGT:30:30, DFG:30:20, XYZ:0:10]]
Most likely a better idea: Split + Stream
Honestly speaking, I didn't know that split can directly be turned into a Stream. It basically leverages the Pattern.compile(yourRegex).splitAsStream(yourInput). As I said, this is a long split way but as the split are dispatched in Port constructor and PortObject constructor, it makes it easier to read:
Put in code, it is much shorter:
public static void main(String[] args) throws IOException {
// the input
String a = "PORT:AXN,0,10;BGT,20,30;CXZ,10,30|BENCH:AXN,50,10;BGT,30,30;DFG,30,20;XYZ,0,10";
// Option 2: Split with Stream:
List<Port> portList2 = Pattern.compile("\\|").splitAsStream(a)
.map(Port::new)
.collect(Collectors.toList());
// Print
System.out.println("PortList2:\n" + portList2 + "\n");
}
Obviously, the output is the same:
PortList2:
[Port:PORT [AXN:0:10, BGT:20:30, CXZ:10:30], Port:BENCH [AXN:50:10, BGT:30:30, DFG:30:20, XYZ:0:10]]

phone Number validation in java

I want to validate a phone number in such Way :-
The field should allow the user to enter characters and should auto-correct. So an entry of "+1-908-528-5656" would not create an error for the user, it would just change to "19085285656".
I also want to number range between 9 to 11.
I also tried with the below code but not concluded to the final solution:
final String PHONE_REGEX = "^\\+([0-9\\-]?){9,11}[0-9]$";
final Pattern pattern = Pattern.compile(PHONE_REGEX);
String phone = "+1-908-528-5656";
phone=phone.replaceAll("[\\-\\+]", "");
System.out.println(phone);
final Matcher matcher = pattern.matcher(phone);
System.out.println(matcher.matches());
You can use simple String.matches(regex) to test any string against a regex pattern instead of using Pattern and Matcher classes.
Sample:
boolean isValid = phoneString.matches(regexPattern);
Find more examples
Here is the regex pattern as per your input string:
\+\d(-\d{3}){2}-\d{4}
Online demo
Better use Spring validation annotation for validation.
Example
// The Regex not validate mobile number, which is in internation format.
// The Following code work for me.
// I have use libphonenumber library to validate Number from below link.
// http://repo1.maven.org/maven2/com/googlecode/libphonenumber/libphonenumber/8.0.1/
// https://github.com/googlei18n/libphonenumber
// Here, is my source code.
public boolean isMobileNumberValid(String phoneNumber)
{
boolean isValid = false;
// Use the libphonenumber library to validate Number
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
Phonenumber.PhoneNumber swissNumberProto =null ;
try {
swissNumberProto = phoneUtil.parse(phoneNumber, "CH");
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}
if(phoneUtil.isValidNumber(swissNumberProto))
{
isValid = true;
}
// The Library failed to validate number if it contains - sign
// thus use regex to validate Mobile Number.
String regex = "[0-9*#+() -]*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(phoneNumber);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}
Assuming your input field take any kind of character and you just want the digits.
String phone = "+1-908-528-5656";
phone=phone.replaceAll("[\\D]","");
if(phone.length()>=9 || phone.length()<=11)
System.out.println(phone);
We can use String.matches(String regex)1 to validate phone numbers using java.
Sample code snippet
package regex;
public class Phone {
private static boolean isValid(String s) {
String regex = "\\d{3}-\\d{3}-\\d{4}"; // XXX-XXX-XXXX
return s.matches(regex);
}
public static void main(String[] args) {
System.out.println(isValid("123-456-7890"));
}
}
P.S. The regex pattern we use extra '\' for escaping when we use in java string. (Try to use "\d{3}-\d{3}-\d{4}" in java program, you will get an error.
Assuming you want an optimization (which is what your comment suggests).
How bout this? (the "0" is to exclude if they give complete garbage without even a single digit).
int parse(String phone){
int num = Integer.parseInt("0"+phone.replaceAll("[^0-9]",""));
return 100000000<=num&&num<100000000000?num:-1;
}
I am not sure but removing the garbage characters parenthesis, spaces and hyphens, if you match with ^((\+[1-9]?[0-9])|0)?[7-9][0-9]{9}$ , you may validate a mobile number
private static final String PHONE_NUMBER_GARBAGE_REGEX = "[()\\s-]+";
private static final String PHONE_NUMBER_REGEX = "^((\\+[1-9]?[0-9])|0)?[7-9][0-9]{9}$";
private static final Pattern PHONE_NUMBER_PATTERN = Pattern.compile(PHONE_NUMBER_REGEX);
public static boolean validatePhoneNumber(String phoneNumber) {
return phoneNumber != null && PHONE_NUMBER_PATTERN.matcher(phoneNumber.replaceAll(PHONE_NUMBER_GARBAGE_REGEX, "")).matches();
}
One easy and simple to use java phone validation regex:
public static final String PHONE_VERIFICATION = "^[+0-9-\\(\\)\\s]*{6,14}$";
private static Pattern p;
private static Matcher m;
public static void main(String[] args)
{
//Phone validation
p = Pattern.compile(PHONE_VERIFICATION);
m = p.matcher("+1 212-788-8609");
boolean isPhoneValid = m.matches();
if(!isPhoneValid)
{
System.out.println("The Phone number is NOT valid!");
return;
}
System.out.println("The Phone number is valid!");
}
i have done testing one regex for this combination of phone numbers
(294) 784-4554
(247) 784 4554
(124)-784 4783
(124)-784-4783
(124) 784-4783
+1(202)555-0138
THIS REGEX SURELY WILL BE WORKING FOR ALL THE US NUMBERS
\d{10}|(?:\d{3}-){2}\d{4}|\(\d{3}\)\d{3}-?\d{4}|\(\d{3}\)-\d{3}-?\d{4}|\(\d{3}\) \d{3} ?\d{4}|\(\d{3}\)-\d{3} ?\d{4}|\(\d{3}\) \d{3}-?\d{4}
Building on #k_g's answers, but for US numbers.
static boolean isValidTelephoneNumber(String number) {
long num = Long.parseLong("0" + number.replaceAll("[^0-9]", ""));
return 2000000000L <= num && num < 19999999999L;
}
public static void main(String[] args) {
var numbers = List.of("+1 212-788-8609", "212-788-8609", "1 212-788-8609", "12127888609", "2127888609",
"7143788", "736103355");
numbers.forEach(number -> {
boolean isPhoneValid = isValidTelephoneNumber(number);
log.debug(number + " matches = " + isPhoneValid);
});
}

How to remove matched words from end of String

I want to remove the following words from end of String ‘PTE’, ‘LTD’, ‘PRIVATE’ and ‘LIMITED’
i tried the code but then i stuck. i tried this
String[] str = {"PTE", "LTD", "PRIVATE", "LIMITED"};
String company = "Basit LTD";
for(int i=0;i<str.length;i++) {
if (company.endsWith(str[i])) {
int position = company.lastIndexOf(str[i]);
company = company.substring(0, position);
}
}
System.out.println(company.replaceAll("\\s",""));
It worked. But suppose the company is Basit LIMITED PRIVATE LTD PTE or Basit LIMITED PRIVATE PTE LTD or any combination of four words in the end. Then the above code just remove the last name i.e., PTE or PRIVATE and so on, and the output is BasitLIMITEDPRIVATELTD.
I want output to be just Basit
How can i do it?
Thanks
---------------Edit---
Please note here the company name is just an example, it is not necessary that it is always the same. may be i have name like
String company = "Masood LIMITED LTD PTE PRIVATE"
or any name that can have the above mentioned words at the end.
Thanks
You can do this in single line. no need to loop through. just use String#replaceAll(regex, str).
company = company.replaceAll("PTE$*?|LTD$*?|PRIVATE$*?|LIMITED$*?","");
If you place the unwanted words in the map it will be ommitted in the resultant string
HashMap map = new HashMap();
map.put("PTE", "");
map.put("LTD", "");
map.put("PRIVATE", "");
map.put("LIMITED", "");
String company = "Basit LTD PRIVATE PTE";
String words[] = company.split(" ");
String resultantStr = "";
for(int k = 0; k < words.length; k++){
if(map.get(words[k]) == null) {
resultantStr += words[k] + " ";
}
}
resultantStr = resultantStr.trim();
System.out.println(" Trimmed String: "+ resultantStr);
If you want to remove these suffixes only at the end of the string, then you could introduce a while loop:
String[] str = {"PTE", "LTD", "PRIVATE", "LIMITED"};
boolean foundSuffix = true;
String company = "Basit LTD";
while (foundSuffix) {
foundSuffix = false;
for(int i=0;i<str.length;i++) {
if (company.endsWith(str[i])) {
foundSuffix = true;
int position = company.lastIndexOf(str[i]);
company = company.substring(0, position);
}
}
}
System.out.println(company.replaceAll("\\s",""));
If you don't mind transforming PTE Basit LIMITED INC to Basit (and also remove the first PTE), then replaceAll should work, as explained by others.
I was trying to do exactly same thing for one of my projects. I wrote this code few days earlier. Now I was exactly trying to find a much better way to do it, that's how I found this Question. But after seeing other answers I decided to share my version of the code.
Collection<String> stopWordSet = Arrays.asList("PTE", "LTD", "PRIVATE", "LIMITED");
String company = "Basit LTD"; //Or Anything
String[] tokens = company.split("[\#\]\\\_\^\[\"\#\ \!\&\'\`\$\%\*\+\(\)\.\/\,\-\;\~\:\}\|\{\?\>\=\<]+");
Stack<String> tokenStack = new Stack<>();
tokenStack.addAll(Arrays.asList(tokens));
while (!tokenStack.isEmpty()) {
String token = tokenStack.peek();
if (stopWordSet.contains(token))
tokenStack.pop();
else
break;
}
String formattedCompanyName = StringUtils.join(tokenStack.toArray());
Try this :
public static void main(String a[]) {
String[] str = {"PTE", "LTD", "PRIVATE", "LIMITED"};
String company = "Basit LIMITED PRIVATE LTD PTE";
for(int i=0;i<str.length;i++) {
company = company.replaceAll(str[i], "");
}
System.out.println(company.replaceAll("\\s",""));
}
All you need is to use trim() and call your function recursively, Or each time you remove a sub string from the end, reset your i to 0.
public class StringMatchRemove {
public static void main(String[] args) {
String str="my name is noorus khan";
String search="noorus";
String newString="";
String word=str.replace(search," ");
StringTokenizer st = new StringTokenizer(word," ");
while(st.hasMoreTokens())
{
newString = newString + st.nextToken() + " ";
}
System.out.println(newString);
}
first using the replace method we get word=my name is ..... khan (Note: here(.) represents the space). Now we should have to remove these spaces for that we are creating a new string adding all the token simply.
Output: my name is khan

Categories

Resources