标题:求助,各位,关于过滤字符的一题
只看楼主
uc8410553
Rank: 1
等 级:新手上路
帖 子:6
专家分:0
注 册:2012-9-23
结帖率:0
 问题点数:0 回复次数:0 
求助,各位,关于过滤字符的一题
以下程序将输入的字符串中的非法字符(<>等)过滤掉。
要求用位运算进行改写。
方法为,定义一个16个元素的Byte类型的数组,一共128位,来表示128个ASCII字符,将非法字符对应位置1,合法字符对应位置0
然后采用位运算来判断。

class Program
    {
        static void Main(string[] args)
        {
            string s = Console.ReadLine();
            foreach (char c in s)
            {
                if (!IsSpecialCharacter(c))
                    Console.Write(c);
            }
        }
        static bool IsSpecialCharacter(char x)
        {
            if (x=='<'||x=='>'||x == '.' || x == '*' || x == '!' || x == '{' || x == '}' || x == '%' || x == ',' || x == '@' || x == '&' || x == '\0' || x == '(' || x == ')' || x == ' ')
            {
                return true;
            }
            else
            {
                return false;
            }      
        }
    }

           //ASCII
         //!=>33
        //%=>37
        //&=>38
        //(=>40
        //)=>41
        //*=>42
        //<60
        //=61
        //>62
        //@=>64
        //{=>123
        //}=>125

然后,下面是我的答案,不知道那里错了,还有byte怎么用,int人说浪费空间。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace filter//过滤非法字符
{
    class Program
    {
        
             static void Main(string[] args)
        {
            string s = Console.ReadLine();
            int[] ascll = new int[16]{128,0,16,24,140,84,0,21,0,0,0,0,0,0,0,20};
            int i=0,j=0,l=0;
            foreach (char c in s)
            {
                         for (; i < 16; i++)
                         {
                             for (; j < 8; j++)
                             {
                                 if (((ascll[i] >> j) & 1) == 1)
                                 {
                                     l = i * 8 + j + 1;
                                     if (c != (char)(l))
                                         Console.Write(c);
                                 }
                             }
                   }
                }
            Console .ReadKey ();
        }
    }
}
搜索更多相关主题的帖子: 元素 字符串 过滤 
2012-10-25 23:55



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-384450-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.053950 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved