如何重复字符串的字符,生成与另一目标字符串长度相同的新字符串?
问题解决方案
核心实现逻辑:获取参考字符串的长度作为目标长度,将短字符串重复拼接至总长度不小于目标长度后,截取前N位(N为目标长度)即可得到匹配长度的结果。
Python 实现
# 定义参考字符串和待重复的短字符串 ref_str = "thermostat" repeat_str = "ice" # 计算需要重复的次数,多重复1次避免长度不够,最后切片取前len(ref_str)位 res = (repeat_str * (len(ref_str) // len(repeat_str) + 1))[:len(ref_str)] print(res) # 输出结果:iceiceicei
JavaScript 实现
const refStr = "thermostat" const repeatStr = "ice" // 用ceil向上取整计算重复次数,repeat后截取前refStr.length位 const res = repeatStr.repeat(Math.ceil(refStr.length / repeatStr.length)).slice(0, refStr.length) console.log(res) // 输出结果:iceiceicei
Java 实现
public class RepeatStr { public static void main(String[] args) { String refStr = "thermostat"; String repeatStr = "ice"; int targetLen = refStr.length(); StringBuilder stringBuilder = new StringBuilder(); // 循环拼接直到长度大于等于目标长度 while (stringBuilder.length() < targetLen) { stringBuilder.append(repeatStr); } // 截取前targetLen位得到结果 String res = stringBuilder.substring(0, targetLen); System.out.println(res); // 输出结果:iceiceicei } }
内容的提问来源于stack exchange,提问作者pepsiMaxFan
相关产品推荐
相关产品推荐

