输入一个字符串后,防止字符串中的空格

时间:2016-11-18 15:27:56

标签: android string substring whitespace

我制作了一个代码,用户无法在字符串中输入第一个空格。 最少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());
		}
	    }
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:1)

使用正则表达式pattern。我made one符合您的要求。

\S{2}\S*\s\S*\n

Explanation:
\S{2} two non whitespace
\S* n non whitespace
\s a whitespace
\S* n non whitespace
\n newline (i only added that for regexr, you may not need it)

替代方式: 迭代String.charAt(int),如果前两个字符中有空格,则返回false,计算所有空格,如果n>,则返回false。 1。

答案 1 :(得分:1)

此方法应符合您的要求:

private static boolean isValidFirstName(String firstName) {
    if (firstName != null && !firstName.startsWith(" ")) {
        int numberOfSpaces = firstName.length() - firstName.replace(" ", "").length();
        if (firstName.length() < 2 || numberOfSpaces <= 1) {
            return true;
        }
    }
    return false;
}

答案 2 :(得分:0)

您需要做的是使用TextWatcher

public class CustomWatcher implements TextWatcher {

private String myText;
private int count = 0;

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after){
    myText= s;
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

}

@Override
public void afterTextChanged(Editable s) {
    //check if there is a space in the first 2 characters, if so, sets the string to the previous before the space
    if(s.length() < 3 && s.contains(" "))
        s= myText;

    //if the length is higher than 2, and the count is higher than 0 (1 space added already), puts the string back if a space is entered
    else if(s.contains(" ") && count > 0)
        s= myText;

    //If none of the above is verified and you enter a space, increase count so the previous if statement can do its job
    else if(s.contains(" "))
        count++;

}

}

然后,将其设置为EditText

mTargetEditText.addTextChangedListener(new CustomWatcher());

答案 3 :(得分:0)

您可以使用TextWatcher控制editText(我假设),如果长度为&lt; 2,则只需检查afterTextChanged(),否则如果字符串包含char&#34; &#34;