简体   繁体   English

在java中将整数和字符转换为字符串

[英]Converting an integer and a character to a string in java

I'm trying to create a string comprised of a single letter, followed by 4 digits eg b6789. 我正在尝试创建一个由单个字母组成的字符串,后跟4个数字,例如b6789。 I'm getting stuck when I try to convert a character, and integer to one String. 当我尝试将字符和整数转换为一个字符串时,我会陷入困境。 I can't use toString() because I've overwritten it, and I assume that concatenation is not the best way to approach it? 我不能使用toString(),因为我已经覆盖了它,我认为连接不是最好的方法吗? This was my solution, until I realised that valueof() only takes a single parameter. 这是我的解决方案,直到我意识到valueof()只接受一个参数。 Any suggestions? 有什么建议么? FYI - I'm using Random, because I will be creating multiples at some point. 仅供参考 - 我使用随机,因为我会在某些时候创建倍数。 The rest of my code seemed irrelevant, and hence has been omitted. 我的其余代码似乎无关紧要,因此被省略了。

   Random r = new Random();

   Integer numbers = r.nextInt(9000) + 1000;

   Character letter = (char)(r.nextInt(26) + 'a');

   String strRep = String.valueOf(letter, numbers);

I think they mean for you not to use concatenation with + operator. 我认为它们意味着你不要使用+运算符连接。

Rather than that, there's a class called StringBuilder which will do the trick for you. 而不是那个,有一个名为StringBuilder的类可以帮助你。 Just create an empty one, append anything you need on it (takes Objects or primitives as arguments and does all the work for you), and at the end, just call at its "toString()" method, and you'll have your concatenated String. 只需创建一个空的,添加你需要的任何东西(将对象或基元作为参数并为你完成所有工作),最后,只需调用其“toString()”方法,你就可以得到你的连接字符串。

For example 例如

StringBuilder sb = new StringBuilder();
sb.append("Foo");
sb.append(123);
return sb.toString();

would return the string Foo123 将返回字符串Foo123

you can use: 您可以使用:

Character.toString(char)

which is 是的

String.valueOf(char)

in reality which also works. 在现实中也有效。 or just use 或者只是使用

String str = "" + 'a';

as already mentioned but not very efficient as it is 正如已经提到的那样,但并不是很有效

String str = new StringBuilder().append("").append('a').toString();

in reality. 事实上。

same goes for integer + string or char + int to string. 对于整数+字符串或char + int到字符串也是如此。 I think your simpliest way would be to use string concatenation 我认为你最简单的方法是使用字符串连接

看起来像你想要的

String.valueOf(letter).concat(numbers.toString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM