简体   繁体   English

Java - 生成长度为 x 的字符串

[英]Java - Generating strings of length x

I have some 'heavy' string manipulation in my Java program, which often involves iterating through a String and replacing certain segments with filler characters , usually "@".我的 Java 程序中有一些“繁重”的字符串操作,通常涉及遍历字符串并用填充字符(通常是“@”)替换某些段。 These are characters are later removed but are used so that the length of the String and the current index are kept intact during the iteration.这些字符后来被删除但被使用,以便在迭代期间 String 的长度和当前索引保持不变。

This process usually involves replacing more than 1 character at a time.此过程通常涉及一次替换 1 个以上的字符。
eg例如
I might need to replace "cat" with "@@@" in the string "I love cats" , giving "I love @@@s" , So often I need to create strings of "@" with x length.我可能需要在字符串"I love cats"中用"@@@"替换"cat" ,给出"I love @@@s" ,所以我经常需要创建长度为x的 "@" 字符串。

In python, this is easy.在 python 中,这很容易。

NewString = "@" *x

In Java, I find my current method revolting.在 Java 中,我发现我目前的方法令人反感。

String NewString = "";
for (int i=0; i< x; i++)  {  
    NewString = NewString.concat("@");  }

Is there a proper, pre-established method for doing this?是否有适当的、预先确定的方法来执行此操作?
Does anybody have a shorter, more 'golfed' method?有人有更短、更“打高尔夫球”的方法吗?
Thanks!谢谢!


Specs:眼镜:
Java SE (Jre7) Java SE (Jre7)
Windows 7 (32) Windows 7 (32)

It's not clear to me what kind of regex the comments are suggesting, but creating a string filled with a particular character to the given length is pretty easy:我不清楚评论建议使用哪种正则表达式,但是创建一个用特定字符填充到给定长度的字符串非常容易:

public static String createString(char character, int length) {
    char[] chars = new char[length];
    Arrays.fill(chars, character);
    return new String(chars);
}

Guava has a nice little method Strings.repeat(String, int) . Guava 有一个不错的小方法Strings.repeat(String, int) Looking at the source of that method, it basically amounts to this:查看该方法的来源,它基本上是这样的:

StringBuilder builder = new StringBuilder(string.length() * count);
for (int i = 0; i < count; i++) {
  builder.append(string);
}
return builder.toString();

Your way of building a string of length N is very inefficient.您构建长度为 N 的字符串的方法非常低效。 You should either use StringBuffer with its convenient append method, or build an array of N characters, and use the corresponding constructor of the String .您应该使用StringBuffer及其方便的append方法,或者构建N个字符的数组,并使用String的相应构造函数。

Can you always use the same characters in the "filler" String and do you know the maximum value of x ?您能否始终在“填充”字符串中使用相同的字符并且您知道x的最大值吗? The you can create a constant upfront which can be cut to arbitrary length:你可以预先创建一个常量,它可以被切割成任意长度:

private static final FILLER = "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@";

// inside your method
String newString = FILLER.substring(0, x);

java.lang.String is immutable. java.lang.String是不可变的。 So, concating strings would result in creation of temporary string objects and thus is slow.因此,连接字符串会导致创建临时字符串对象,因此速度很慢。 You should consider using a mutable buffer like StringBuffer or StringBuilder .您应该考虑使用可变缓冲区,如StringBufferStringBuilder Another best practice when working with strings in java is to prefer using CharSequence type wherever possible.在 java 中使用字符串时的另一个最佳实践是尽可能使用CharSequence类型。 This would avoid unnecessary calls to toString() and you can easily change the underlying implementation type.这将避免对toString()的不必要调用,并且您可以轻松更改底层实现类型。

If you are looking for a one liner to repeat strings and this justifies using an external library, have a look at StringUtils.repeat from Apache Commons library.如果您正在寻找一个单一的衬里来重复字符串并且这证明使用外部库是合理的,请查看 Apache Commons 库中的StringUtils.repeat But, I feel you can just write your own code than using another library for a trivial task of repeating strings.但是,我觉得你可以只编写自己的代码,而不是使用另一个库来完成重复字符串的琐碎任务。

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

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