在Java中将带空格的String转换为Integer [英] Converting a String with spaces to an Integer in java

查看:131
本文介绍了在Java中将带空格的String转换为Integer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将String变量转换为整数,只有String看起来像这样(例如):

I'm trying to convert a String variable into an integer, only the String looks like this (for example):

String string = " 12";

因此String前面有一个空格。现在正在从.txt文件中读取String变量,这就是为什么我遇到了在它前面有空间的问题。我需要将变量转换为int,但是当我尝试时:

And so the String has a space in front of it. Now the String variable is being read from a .txt file which is why I'm having the issue of having the space in front of it. I need to convert the variable into an int, but when I try:

int integer = Integer.parseInt(string);

将String传递给一个整数,它编译但是在尝试运行程序时遇到错误,因为有空格作为字符串的一部分。

to pass the String into an integer, it compiles but I get an error when trying to run the program, since there is white space as part of the String.

有没有办法将前面有空格的数字串传递给int? .trim会工作吗?如果是这样,我将如何使用它? (我对.trim不是很熟悉,我还在学习!!)我很感激你的帮助! ^ _ ^

Is there a way to pass a String of numbers with a space in front of it into an int? Would .trim work? And if so, how would I use that? (I'm not very familiar with .trim, I'm still learning!!) I appreciate the help! ^_^

推荐答案


.trim会工作吗?如果是这样,我将如何使用它?

Would .trim work? And if so, how would I use that?

是, trim()将起作用,它将从 String 中移除前导和尾随空格,

Yes, trim() will work, it will remove leading and trailing spaces from String,

int integer = Integer.parseInt(string.trim());

这篇关于在Java中将带空格的String转换为Integer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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