检查字符是整数还是字母

如何解决检查字符是整数还是字母

| 我正在使用Java修改文件。这是我要完成的工作: 如果在读取时检测到&符号以及整数,我想删除&符号并将整数转换为二进制。 如果在读取时检测到&符号以及一个(随机)单词,我想删除&符号并用整数16替换该单词,并且是否要与&符号一起使用不同的字符串,我想将数字1设置为大于整数16。 这是我的意思的一个例子。如果输入的文件包含以下字符串:
&myword
&4
&anotherword
&9
&yetanotherword
&10
&myword
输出应为:
&0000000000010000 (which is 16 in decimal)
&0000000000000100 (or the number \'4\' in decimal)
&0000000000010001 (which is 17 in decimal,since 16 is already used,so 16+1=17)
&0000000000000101 (or the number \'9\' in decimal)
&0000000000010001 (which is 18 in decimal,or 17+1=18)
&0000000000000110 (or the number \'10\' in decimal)
&0000000000010000 (which is 16 because value of myword = 16)
这是我到目前为止尝试过的,但尚未成功:
for (i=0; i<anyLines.length; i++) {
            char[] charray = anyLines[i].toCharArray();
            for (int j=0; j<charray.length; j++)
                      if (Character.isDigit(charray[j])) {
                          anyLines[i] = anyLines[i].replace(\"&\",\"\");
                          anyLines[i] = Integer.toBinaryString(Integer.parseInt(anyLines[i]);
                          }
                       else {
                          continue;
                            }
                        if (Character.isLetter(charray[j])) {
                          anyLines[i] = anyLines[i].replace(\"&\",\"\");
                          for (int k=16; j<charray.length; k++) {
                            anyLines[i] = Integer.toBinaryString(Integer.parseInt(k);
                            }

                        }

                     }
                    }
我希望我能表达清楚。关于如何完成此任务的任何建议?     

解决方法

Character.isLetter() //tests to see if it is a letter
Character.isDigit() //tests the character to
    ,看起来您可以针对正则表达式进行匹配。我不懂Java,但是您应该至少拥有一个正则表达式引擎。那么正则表达式将是: regex1:&(\\ d +) 和 regex2:&(\\ w +) 要么 regex3:&(\\ d + | \\ w +) 在第一种情况下,如果regex1匹配,则您知道遇到了一个数字,并且该数字进入了第一个捕获组(例如:match.group(1))。如果regex2匹配,则说明您有一个单词。然后,您可以将该单词查找到词典中,查看其关联编号是什么,或者如果不存在该编号,则将其添加到词典中,并将其与下一个空闲编号(16 +词典大小+ 1)关联。 另一方面,regex3会同时匹配数字和单词,因此您可以查看捕获组中的内容(这只是另一种方法)。 如果两个正则表达式都不匹配,则您的序列无效,或者您需要采取其他措施。请注意,正则表达式中的\\ w仅匹配单词字符(即字母,_和其他一些字符),因此&çSomeWord或&* SomeWord根本不匹配,而在&Hello.World中捕获的组将是只是“你好”。 正则表达式库通常为匹配的文本提供长度,因此您可以将i向前移动那么多,以跳过已经匹配的文本。     ,您必须以某种方式标记您的输入。似乎您将其分成几行,然后分别分析每行。如果这是您想要的,那就好。如果不是,您可以简单地搜索
&
indexOf(\'%\')
),然后以某种方式确定下一个标记是什么(数字或\“ word \”,但是您要定义单词)。 您要如何处理与模式不匹配的输入?任务的描述或示例均未真正涵盖这一点。 您需要具有已读字符串的字典。用
Map<String,Integer>
。     ,我会将其发布为评论,但还没有能力。您遇到的问题是什么?错误?结果不正确? 16 \没有正确递增?同样,这些示例使用\'%\',但是在您的描述中您说它应该以\'&\'开头。 Edit2:认为它是一行一行的,但是重新阅读表明您可能想要找到说“我去了&store \”,并希望它说“我去了&000010000 \”。因此,您需要按空格分割,然后进行迭代,然后将字符串传递到\'replace \'方法中,该方法类似于下面的内容。 Edit1:如果我了解您要执行的操作,则应使用类似这样的代码。
Map<String,Integer> usedWords = new HashMap<String,Integer>();
    List<String> output = new ArrayList<String>();
    int wordIncrementer = 16;
    String[] arr = test.split(\"\\n\");
    for(String s : arr)
    {
        if(s.startsWith(\"&\"))
        {
            String line = s.substring(1).trim(); //Removes &
            try
            {
                Integer lineInt = Integer.parseInt(line);
                output.add(\"&\" + Integer.toBinaryString(lineInt));
            }
            catch(Exception e)
            {
                System.out.println(\"Line was not an integer.  Parsing as a String.\");
                String outputString = \"&\";
                if(usedWords.containsKey(line))
                {
                    outputString += Integer.toBinaryString(usedWords.get(line));
                }
                else
                {
                    outputString += Integer.toBinaryString(wordIncrementer);
                    usedWords.put(line,wordIncrementer++); 
                }
                output.add(outputString);
            }
        }
        else
        {
            continue; //Nothing indicating that we should parse the line.
        }
    }
    ,这个怎么样?
String input = \"&myword\\n&4\\n&anotherword\\n&9\\n&yetanotherword\\n&10\\n&myword\";
String[] lines = input.split(\"\\n\");

int wordValue = 16;

// to keep track words that are already used
Map<String,Integer> wordValueMap = new HashMap<String,Integer>();

for (String line : lines) {
    // if line doesn\'t begin with &,then ignore it
    if (!line.startsWith(\"&\")) {
        continue;
    }

    // remove &
    line = line.substring(1);

    Integer binaryValue = null;

    if (line.matches(\"\\\\d+\")) {
        binaryValue = Integer.parseInt(line);
    }
    else if (line.matches(\"\\\\w+\")) {
        binaryValue = wordValueMap.get(line);

        // if the map doesn\'t contain the word value,then assign and store it
        if (binaryValue == null) {
            binaryValue = wordValue;
            wordValueMap.put(line,binaryValue);
            wordValue++;
        }
    }

    // I\'m using Commons Lang\'s StringUtils.leftPad(..) to create the zero padded string
    String out = \"&\" + StringUtils.leftPad(Integer.toBinaryString(binaryValue),16,\"0\");
    System.out.println(out);
这是打印输出:-
&0000000000010000
&0000000000000100
&0000000000010001
&0000000000001001
&0000000000010010
&0000000000001010
&0000000000010000
仅供参考,10的二进制值为\“ 1010 \”,而不是原始帖子中所述的\“ 110 \”。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-