简体   繁体   English

如何形成一个包含从 0 到 n 的数字的字符串

[英]How can I form a string containing numbers from 0 to n

For eg when n = 5 , I need to generate a string "012345" .例如,当n = 5 ,我需要生成一个字符串"012345"

I could do it by running a for loop from 0 to n and appending numbers to a string.我可以通过运行从0nfor循环并将数字附加到字符串来实现。

for(int i = 0; i <= n; i++) {
    s += i;
}

Is there a simple way of doing it without the for loop?有没有没有for循环的简单方法? Perhaps using streams?也许使用流?

I think the best way to do this is the way you're already done it in your Question using a loop.我认为最好的方法是你已经在你的问题中使用循环完成了它。 Reading the comments, it seems to be the general consensus.阅读评论,这似乎是普遍的共识。 Nikolas Charalambidis pointed out in a comment that the solution could do with a StringBuilder instead: Nikolas Charalambidis评论中指出,该解决方案可以使用StringBuilder代替:

StringBuilder s = new StringBuilder();
for(int i = 0; i <= n; i++) {
  s.append(i);
}

If you must use a Stream , I believe the accepted Answer is the way to go because如果您必须使用Stream ,我相信接受的答案是要走的路,因为

  1. I think it just looks "clean" and我认为它只是看起来“干净”而且
  2. It also uses StringBuilder instead of String .它还使用StringBuilder而不是String There are other approaches though.还有其他方法。

One approach is relying on side-effects.一种方法是依赖副作用。 Create a variable and update it from within the stream.创建一个变量并从流中更新它。 The JavaDoc on Package java.util.stream warns about the use: 包 java.util.stream上的 JavaDoc 警告使用:

Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement, as well as other thread-safety hazards.通常不鼓励流操作的行为参数的副作用,因为它们通常会导致在不知情的情况下违反无状态要求,以及其他线程安全危险。

String[] alternativeWayA = {""};
IntStream.rangeClosed(0,n).forEach(i -> alternativeWayA[0] = alternativeWayA[0] + i);

Luiggi Mendoza mentions in one comment Luiggi Mendoza在一条评论中提到

You could use collect(Collectors.joining()) and have the same output您可以使用collect(Collectors.joining())并具有相同的输出

and in another comment并在另一条评论中

Well, you could use boxed before calling collect好吧,你可以在调用collect之前使用boxed

String alternativeWayB = IntStream.rangeClosed(0,n)
                                  .boxed()
                                  .map(i -> i.toString())
                                  .collect(Collectors.joining(""));

..if one prefers using reduce instead of Collectors.joining : ..如果人们更喜欢使用reduce而不是Collectors.joining

String alternativeWayC = IntStream.rangeClosed(0,n)
                                  .boxed()
                                  .map(i -> i.toString())
                                  .reduce("", String::concat);

..or as Nikolas Charalambidis suggests in this comment ..或者正如Nikolas Charalambidis在此评论中所建议的那样

you need to mapToObj as this collector is not available for IntStream您需要mapToObj因为此收集器不可用于IntStream

String alternativeWayD = IntStream.rangeClosed(0,n)
                                  .mapToObj(i -> String.valueOf(i))
                                  .collect(Collectors.joining(""));

Holger posted a comment with Holger发表了评论

String string = new String(IntStream.rangeClosed('1', '1'+n).toArray(), 0, n);

which I think is very elegant and works for n < 10 .我认为它非常优雅,适用于n < 10 For n = 15 the result becomes 0123456789:;<=>?对于n = 15 ,结果变为0123456789:;<=>? since it's using integer values of characters.因为它使用字符的整数值。 I added a + 1 to the last parameter of the String constructor:我在String构造函数的最后一个参数中添加了一个+ 1

String alternativeWayE = new String(IntStream.rangeClosed('0', '0'+n).toArray(), 0, n + 1);

Use IntStream and StringBuilder :使用IntStreamStringBuilder

int n = 5;
String string = IntStream.rangeClosed(0, n)
     .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
     .toString();

However, for this particular case it's better to use a for-loop with StringBuilder .但是,对于这种特殊情况,最好将 for 循环与StringBuilder

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

相关问题 如何从两个 n 位二进制数创建一个 2n 位二进制数? - How can i create from two n-bit binary numbers a 2n-binary number? 如何在Java 8中找到N个数字中最大的M个数字? - How can I find the largest M numbers from N numbers in Java 8? 如何从包含数字和字母的字符串中读取一个 int 数字? - How to read an int number from a string containing numbers and letters? 如何从这2个数组中生成一组固定数量的数字? - How can I generate a string of set amount of numbers from these 2 arrays? 如何使用包含空格的信用卡号? - How can I use credit card numbers containing spaces? 如何从包含需要保留某些数字的数字的字符串中获取字符串? - How to get string from a string containing numbers where certain numbers need to remain? 我如何获得最小数量的ArrayList <Integer> 需要具有从1到“ n”的所有数字吗? - how I can get the minimum number of ArrayList<Integer> needed to have all numbers from 1 to “n”? 如何打印出满足条件的 n 个数字 - How can I print out n numbers that satisfy the condition 如何在Java中将“ \\ n”(字符串)转换为“ \\ n”(字符) - How can I turn “'\n'” (String) into '\n' (char) in java 如何从字符串中删除“”,以便可以将数字字符串转换为整数? - how to I remove the “” from a String so that I can convert a string with numbers to integer?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM