如何确定字符串是否包含整数? [英] How to determine whether a string contains an integer?

查看:47
本文介绍了如何确定字符串是否包含整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个要测试的字符串,以确保在继续其他代码之前,该字符串包含整数.在Java中,您将使用什么来确定它是否为整数?

Say you have a string that you want to test to make sure that it contains an integer before you proceed with other the rest of the code. What would you use, in java, to find out whether or not it is an integer?

推荐答案

如果要确保它是 only 一个整数并将其转换为一个整数,我将使用正则表达式: stringVariable.matches("\\ d")

If you want to make sure that it is only an integer and convert it to one, I would use parseInt in a try/catch. However, if you want to check if the string contains a number then you would be better to use the String.matches with Regular Expressions: stringVariable.matches("\\d")

这篇关于如何确定字符串是否包含整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆