Sudhanshu Gaur
Sudhanshu Gaur

Reputation: 7664

Retrieve a SubString from a String in the fastest possible way. Format from the end is fixed but not from the beginning, and Length is also not fixed

I have a String which contains the current location of a person. Now i want to retrieve two strings which appears before the city name, the string is like here

Unnamed Road, Lal Qila, Chandni Chowk, New Delhi, City 110006, India. 

here I want to extract Chandni Chowk, New Delhi. But also remember city name can be of any length. Below is my code can u pls reduce the time complexity

var c = 0;
            var arr = [];
            for(var i = location.length - 15; i >= 0; i--){
                if (c > 2) {
                    break;
                }
                if (location[i] == ",") {
                    c++;
                    arr.push(i);
   //               arr[c] = i;
                }
            }
            if (c == 2) {
                final_location = location.substring(arr[1] + 2, arr[0]);
            } else if (c == 3){
                final_location = location.substring(arr[2] + 2, arr[0]);
            }

Thanks a lot guys for all of ur help

Upvotes: 1

Views: 107

Answers (5)

Vibhesh Kaul
Vibhesh Kaul

Reputation: 2613

If the formatting is fixed from the end you could use it this way, This is an edit based on the op's request

var split = 'Unnamed Road, Lal Qila, Chandni Chowk, New Delhi, City 110006, India'.split(',');

var Area= split[split.length-5];// will have Chandni Chowk
var City= split[split.length-4];// will have New Delhi

Upvotes: 3

Alex K.
Alex K.

Reputation: 175766

You can:

var parts = addrString.split(',').slice(2, 4).toString();

> "Chandni Chowk, New Delhi"

After your comment, offset from the total length:

var addr = "Unnamed Road, Lal Qila, XXXXX, Chandni Chowk, New Delhi, City 110006, India"

var arr = addr.split(',');
var parts = arr.slice(arr.length - 4, arr.length - 2).toString();

> "Chandni Chowk, New Delhi"

Upvotes: 2

Dici
Dici

Reputation: 25950

Just split the string by comma. To make it faster, compile the pattern just once and use it several times :

Pattern commaSeparated = Pattern.compile(",");
...
String address = "Unnamed Road, Lal Qila, Chandni Chowk, New Delhi, City 110006, India";
String[] split = commaSeparated.split(address);
// get the indices you want in split

Upvotes: 1

Yindy
Yindy

Reputation: 36

If the entrys are always seperated by ',' you can use something like:

String[] temp = entryString.split(",");

and your desired Strings would be found in temp[2] and temp[3].

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

You may use the below positive lookahead based regex.

Pattern p = Pattern.compile("\\b[^,]*,[^,]*(?=,\\s*\\bCity 110006\\b)");
Matcher m = p.matcher(s);
if(m.find())
{
System.out.println(m.group());
}

DEMO

Upvotes: 1

Related Questions