eclipse 如何从编辑文本中获取前三个字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23925220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get first three characters from an edittext?
提问by user3686028
I want to get the first three characters from an edittext and then turn them onto a string, but I cant find anything about that. Any ideas?
我想从编辑文本中获取前三个字符,然后将它们转换为字符串,但我找不到任何相关信息。有任何想法吗?
回答by cjbrooks12
To get text from an EditText, or a TextView, Button, etc. (pretty much any View that has text), you call getText(). This returns a CharSequence, which is almosta String, but not quite, so to turn it into a String object, call toString() on it. And then to get the first 3 letters, use the substring() method, where the first argument is the index of the character to start, and the second is one past the lastcharacter you want. So you want the first 3 characters, which are indices 0,1,2, so we must have 3.
要从 EditText 或 TextView、Button 等(几乎所有具有文本的视图)获取文本,您可以调用 getText()。这将返回一个 CharSequence,它几乎是一个字符串,但不完全是,因此要将其转换为 String 对象,请对其调用 toString()。然后要获取前 3 个字母,请使用 substring() 方法,其中第一个参数是要开始的字符的索引,第二个参数是您想要的最后一个字符之后的一个。所以你想要前 3 个字符,它们是索引 0、1、2,所以我们必须有 3。
EditText yourEditText = (EditText) findViewById(R.id.your_edit_text);
CharSequence foo = yourEditText.getText();
String bar = foo.toString();
String desiredString = bar.substring(0,3);
In addition, you will probably want to make sure that the user has actually put something in the EditText before assuming that there is and getting a NullPointerException when you try to use the string. So i usually use EditTexts in the following way.
此外,在您尝试使用该字符串时,您可能希望在假设存在并获得 NullPointerException 之前确保用户实际已将某些内容放入 EditText。所以我通常按以下方式使用 EditTexts。
EditText yourEditText = (EditText) findViewById(R.id.your_edit_text);
String foo = yourEditText.getText().toString();
if(foo.length() > 0) { //just checks that there is something. You may want to check that length is greater than or equal to 3
String bar = foo.substring(0, 3);
//do what you need with it
}
回答by Neal
EditText mEditText = (EditText)findViewById(R.id.edit_text);
String mString = mEditText.getText().toString().substring(0,3);
回答by alfasin
EditText tEdit = (EditText)findViewById(R.id.edittext);
String text = tEdit.getText().toString();
System.out.println(text.substring(0,3));
回答by Sebastien Bianchi
You can do the following:
您可以执行以下操作:
mEditText.getText().toString().substring(0,3);
mEditText.getText().toString().substring(0,3);