Detect and count special Characters in EditText - Android

冷暖自知 提交于 2020-01-15 08:19:50

问题


So, I'm making an Application which includes Send Texts to each other. This will be sent through the server, and won't have anything to do with the phone (companies) itself.

We (My company and I) chose to put a maximum amount of characters. - 612.

So, You can use 612 character spaces.

I've noticed that Special Characters such as: é, ñ, á, è, à etc... use more than 1 spot. Since the country (Spain) we work in, uses a lot of special characters such as those, we chose that IF the person types in one of the special characters, instead of using 1 spot, use 2 spots.

So basically what I want to do, is, as the person is typing, count the amount of special characters and "-1" on the amount of characters remaining.

I haven't tried much to be honest, because I couldn't find anything relevant to this situation.

Here's my Method. (Oh, and the EditText + Buttons etc are in a Dialog.)

 private void smsPopUp() {
        // TODO Auto-generated method stub
        final Dialog smsDialog = new Dialog(this);
        smsDialog.setContentView(R.layout.sms_dialog);


        smsDialog.setCanceledOnTouchOutside(false);
        Button cancelsms = (Button)smsDialog.findViewById(R.id.smsCancel);
        EditText SmsText = (EditText) smsDialog.findViewById(R.id.etSmsText);

        final TextView dialogCharCount = (TextView) smsDialog.findViewById(R.id.tvCharCount);

        SmsText.addTextChangedListener(new TextWatcher(){
            int i = 0;
            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                i = 612 - s.length();
                dialogCharCount.setText(String.valueOf(i) + " Characters Remaining..");

            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after){}
            public void onTextChanged(CharSequence s, int start, int before, int count){}

        });



        smsDialog.setTitle("To: " + numberfield.getText());

        cancelsms.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v) 
            {           

                smsDialog.dismiss();
            }
        });

        smsDialog.show();

    }

(The app looks bad, but it's a start!)

--- Current Code ---

SmsText.addTextChangedListener(new TextWatcher(){
            int i = 0;
            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                String str = s.toString();
                int specialCounter = 0;
                //Loop through chars 
                for (int i = 0, len = str.length(); i < len; ++i) {
                    Character c = str.charAt(i);
                    if (c == 'ñ' 
                     || c == 'á' || c == 'à' || c == 'ã' || c == 'â' || c == 'ä' //a
                     || c == 'Á' || c == 'À' || c == 'Ã' || c == 'Â' || c == 'Ä' //A
                     || c == 'é' || c == 'è' || c == 'ÿ' || c == 'ê' || c == 'ë' //e + y
                     || c == 'É' || c == 'È' || c == 'Ÿ' || c == 'Ê' || c == 'Ë' //E + Y
                     || c == 'í' || c == 'ì'             || c == 'î' || c == 'ï' //i
                     || c == 'Í' || c == 'Ì'             || c == 'Î' || c == 'Ï' //I
                     || c == 'ó' || c == 'ò' || c == 'õ' || c == 'ô' || c == 'ö' //o                     
                     || c == 'Ó' || c == 'Ò' || c == 'Õ' || c == 'Ô' || c == 'Ö' //O
                     || c == 'ú' || c == 'ù'             || c == 'û' || c == 'ü' //u
                     || c == 'Ú' || c == 'Ù'             || c == 'Û' || c == 'ü' //U
                     ) {
                         specialCounter++;
                    }
                }

                i = 612 - s.length() - specialCounter;
                dialogCharCount.setText(String.valueOf(i) + " Characters Remaining..");

            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after){}
            public void onTextChanged(CharSequence s, int start, int before, int count){}

        });

It's rubbish. I know. It get's the job done until I find a smarter and faster way.


回答1:


Just run through inserted text and compare characters

Set<Character> specialChars = new HashSet<Character>();
specialChars.add('é');
// ...
specialChars.add('ñ');

String str = s.toString();
int specialCounter = 0;
for (int i = 0, len = str.length(); i < len; ++i) {
    Character c = str.charAt(i);
    if (specialChars.contains(c)) {
         specialCounter++;
    }
}

int totalRemaining = 612 - s.length() - specialCounter;



回答2:


I would suggest that go for RegEx to do such a task it would give you better efficiency as well as its much easier to use for the long run .

you can try something like this

static int countAlphabets , countSpecialCharacter;

String mesage= "this is the demo text for identifying $ words and special $ %^ characters ! ! @ ";

String pattern4 = "[aA-zZ] "; //REGULAR EXPRESSION for counting character String pattern5 = "!|@|$|%|^"; //REGULAR EXPRESSION for counting special characters

Pattern pattern11 = Pattern.compile(pattern4);
Matcher matcher = pattern11.matcher(mesage);
while(matcher.find())
{
    System.out.println("no of words are "+countAlphabets+++" and still"
            + " counting");

}
Pattern pattern22= Pattern.compile(pattern5);
Matcher matcher1= pattern22.matcher(mesage);
while(matcher1.find())
{
    System.out.println("no of words are "++countSpecialCharacter+++" and still"
            + " counting");

}

leeme know if its useful.




回答3:


you can also check like:

if(!Character.isLetter(str.charAt(i))) {
   //its a special character
   //increase count 
}
else {
  //its a letter
}


来源:https://stackoverflow.com/questions/20635704/detect-and-count-special-characters-in-edittext-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!