【发布时间】:2016-11-18 15:27:56
【问题描述】:
我编写了一个用户无法在字符串中输入第一个空格的代码。 允许用户在最少 2 个字符后输入空格。 我需要重新定义我的方法,以便用户输入一次空格,并且只在两个或多个字符之后输入一次。之后应该防止它。我该怎么做?
case UPDATE_NAME:
if (firstName.getText().toString().startsWith(" "))
firstName.setText(firstName.getText().toString().trim());
if (firstName.getText().toString().contains(" "))
firstName.setText(firstName.getText().toString().replace(" ", " "));
int indexOfSpace = firstName.getText().toString().lastIndexOf(" ");
if (indexOfSpace > 0) {
String beforeSpace = firstName.getText().toString().substring(0, indexOfSpace);
String[] splitted = beforeSpace.split(" ");
if (splitted != null && splitted.length > 0) {
if (splitted[splitted.length - 1].length() < 2)
firstName.setText(firstName.getText().toString().trim());
}
}
【问题讨论】:
标签: android string substring whitespace