Search code examples
javastringsubstringtalend

get 2 characters from a string


I have a string FILENAME which actually holds the file names in a foreach loop. The string will be something like:

MyFile_TEST_INDIA_20160728
MyFile_TEST_AMERICA_20160728    
MyFile_TEST_GERMANY_20160728

I need to get the first 2 characters of the country name. I tried with the below:

String rmtdir = Filename.substring(Filename.length() - 12, Filename.length() - 12);
System.out.println(rmtdir); 

But by using this I could only get the required data for INDIA.
For other countries, I manually need to update the 2nd part of the substring, keeping the extended length of the countries in mind.

Like for America and Germany:

String rmtdir = Filename.substring(Filename.length() - 12, Filename.length() - 14);

Is there any way to go to the starting index and select number of positions to be selected?


Solution

  • Assuming the format is like the two examples, I'd use split() and substring()

     String test = "MyFile_TEST_INDIA_20160728";
     String countryCode = test.split("_")[2].substring(0,2);
     System.out.println(countryCode); // print IN