سؤال

I got confused with substring in android. in my database i have file pdf like this DOGMATIKA-3.pdf and i want to select the "pdf". ho to do it in android? i just want to select 3 last letters , anyone please help me, thank you. i already try with this code but got force close.

package mobile.download;

public class DownloadText extends Activity{
    public Koneksi linkurl;
    public Kondownload linkurl2;
    String url;
    String SERVER_URL;
    String SERVER_URL2;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.linkdownload);

        TextView mTextLink = (TextView) findViewById(R.id.LinkDownload);
        Bundle bundle = this.getIntent().getExtras();

        String param1 = bundle.getString("keyIdc");
        String param2 = bundle.getString("keyReference");
        if(param2.substring(-3, 0).equals("pdf"))
        {
            linkurl = new Koneksi(this);
            SERVER_URL = linkurl.getUrl();
            SERVER_URL += "/moodledata/"+param1+"/"+param2;
            mTextLink.setText(SERVER_URL);
            Pattern pattern = Pattern.compile(SERVER_URL);

           Linkify.addLinks(mTextLink, pattern, "");
        }
        else
        {
            linkurl2 = new Kondownload(param2);
            SERVER_URL2 = linkurl2.getUrl();

            mTextLink.setText(SERVER_URL2);
            Pattern pattern = Pattern.compile(SERVER_URL2);

           Linkify.addLinks(mTextLink, pattern, "");
        }

    }
}
هل كانت مفيدة؟

المحلول

last 3 letters are length() - 3 to length() (the second parameter is implicitely length(), so it is not necessary)

param2.substring(params2.length() - 3)

however, you could use endsWith which is clearer :

param2.endsWith("pdf")

which does exactly that.

نصائح أخرى

try param2.substring(param2.indexOf("."), param2.length()).equals("pdf") instead..

If you are intent on using .substring(), use string.substring(string.length()-3).

However, you can also use the .split() method like so:

String [] split = string.split(".");

This will create a new array excluding all instances of "." and using them as the array separators. In other words, if you called this .split() on your above string, you would get

{"DOGMATIKA-3","pdf"}

The latter method will work for file extensions that are not three characters.

i have file pdf like this DOGMATIKA-3.pdf and i want to select the "pdf"

String test = "myPdf.pdf";
String extension = test.substring(test.lastIndexOf(".")+1, test.length());

Or you can just do :

String extension = test.substring(test.lastIndexOf(".")+1);

just use like that

  String substr = param2.substring(param2.length() - 3);
      if("pdf".equals(substr))
    {
        // use what you want
    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top