zoukankan      html  css  js  c++  java
  • 华为2013年西安java机试题目:如何过滤掉数组中的非法字符。

    这道题目为记忆版本:

    题目2描述:

         编写一个算法,过滤掉数组中的非法字符,最终只剩下正式字符。

          示例:输入数组:“!¥@&HuaWei*&%123”

                  调用函数后的输出结果,数组:“HuaWei123”。

    函数声明:

    public static void getFormatString(String s)

    代码实现如下:

     1 import java.util.ArrayList;
     2 
     3 public class HuaWeiTest {
     4     
     5     public static void main(String[] args){
     6         String str="!&@$HuaWei*&%123";
     7         HuaWeiTest test=new HuaWeiTest();
     8         test.getFormatString(str);
     9         System.out.println("过滤后的字符串是:"+test.getFormatString(str));
    10     }
    11     public static String getFormatString(String s){
    12         //ArrayList<char> list=new ArrayList<String>();
    13         //把String类型的数组转换成char类型的数组,方便比较字符值的大小。
    14         String ret="";
    15         char[] ch=s.toCharArray(); //把字符型变量转换成字符串。
    16         for(int i=0;i<ch.length;i++){
    17             if(('a'<=ch[i]&&ch[i]<='z')||('A'<=ch[i]&&ch[i]<='Z')||('0'<=ch[i]&&ch[i]<'9'))
    18                 ret+=ch[i];    
    19         }
    20         return ret;
    21         
    22     }
    23 }

    TT要学的就是:

    (1)String类型的变量要转换成char类型的,不然是没法比较ASCII码值。在此,我专门查了一下,为什么要把String类型的变量转换成char类型的?

          记住:char[] ch=s.toCharArray();把String类型的变量转变成char类型的变量。

    Ans:

    (2)还有就是不能直接'a'<=ch[i]<='z',而要分开写:'a'<=ch[i]&&ch[i]<='z'? 因为'<='是二元运算符,这是语法。。

  • 相关阅读:
    设计模式系列
    设计模式系列
    设计模式系列- 抽象工厂模式
    设计模式系列
    Python3 系列之 编程规范篇
    【ABAP系列】SAP ABAP BDC_OKCODE 解释
    【ABAP系列】SAP ABAP MIR7预制凭证BAPI
    【ABAP系列】SAP ABAP 的替代和校验
    【ABAP系列】SAP ABAP 开发中的SMARTFORMS 参数
    【ABAP系列】SAP ABAP 实现FTP的文件上传与下载
  • 原文地址:https://www.cnblogs.com/meihao1989/p/3176346.html
Copyright © 2011-2022 走看看