重复字符串的简单方法 [英] Simple way to repeat a string

查看:91
本文介绍了重复字符串的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种简单的commons方法或运算符,该方法或运算符允许我重复一些字符串 n 次.我知道我可以使用for循环编写此代码,但是我希望在必要时避免for循环,并且应该在某个地方存在一个简单的直接方法.

I'm looking for a simple commons method or operator that allows me to repeat some string n times. I know I could write this using a for loop, but I wish to avoid for loops whenever necessary and a simple direct method should exist somewhere.

String str = "abc";
String repeated = str.repeat(3);

repeated.equals("abcabcabc");

有关:

重复字符串javascript 通过重复给定数量的另一个字符串来创建NSString次

已编辑

在并非完全必要的情况下,我尝试避免for循环,因为:

I try to avoid for loops when they are not completely necessary because:

  1. 即使将它们塞入另一个函数中,它们也会增加代码行数.

  1. They add to the number of lines of code even if they are tucked away in another function.

阅读我的代码的人必须弄清楚我在for循环中正在做什么.即使它被注释并且具有有意义的变量名称,他们仍然必须确保它没有做任何聪明"的事情.

Someone reading my code has to figure out what I am doing in that for loop. Even if it is commented and has meaningful variables names, they still have to make sure it is not doing anything "clever".

程序员喜欢将聪明的东西放入for循环中,即使我将其写为只做打算做的事情",也不排除有人随便添加一些额外的聪明的"fix".

Programmers love to put clever things in for loops, even if I write it to "only do what it is intended to do", that does not preclude someone coming along and adding some additional clever "fix".

它们通常很容易出错.对于涉及索引的循环,往往会产生一个错误.

They are very often easy to get wrong. For loops involving indexes tend to generate off by one bugs.

For循环经常重复使用相同的变量,从而增加了真正难以发现作用域错误的机会.

For loops often reuse the same variables, increasing the chance of really hard to find scoping bugs.

For循环增加了bug猎人必须寻找的位置.

For loops increase the number of places a bug hunter has to look.

推荐答案

String::repeat

". ".repeat( 7 )  // Seven period-with-space pairs: . . . . . . . 

Java 11的新功能是方法

New in Java 11 is the method String::repeat that does exactly what you asked for:

String str = "abc";
String repeated = str.repeat(3);
repeated.equals("abcabcabc");

查看全文

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