如何从android中的字符串中获取子字符串 [英] how to get a substring from a string in android

查看:708
本文介绍了如何从android中的字符串中获取子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个edittext,第一个将有26个字符的字符串。我需要在第二个edittext中获得fisrt 14个字符。我是怎么做的。



i have 2 edittext, the first one will have a string if 26 characters. i need to get the fisrt 14 characters in the second edittext. how do i do it.

val=(EditText) findViewById(R.id.editText1);
		gtin=(EditText) findViewById(R.id.editText2);
		String sVal=val.getText().toString();
		sVal=sVal.substring(1, 14);
		
		gtin.setText(sVal);





编译时我得到索引超出范围的异常



on compiling i get index out of bound exception

推荐答案

首先检查长度,而不是假设其长度为14或更长。

Check the length first instead of assuming its length is 14 or more.
if(sVal.length() >= 14) 
{
   sVal = sVal.substring(1, 14);
}





祝你好运!



ps。你确定要从1开始而不是字符串中的第一个字符(位置0)?



Good luck!

ps. are you sure you want to start at 1 instead of the first character in the string (at position 0)?


这篇关于如何从android中的字符串中获取子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆