上下文
我希望有一个固定的字符串长度,因为我格式化了一个输出文件,我构建了两个应该根据我的字符串长度应用于字符串的函数。
public String formatSpace(String s, int desiredlength){
while (s.length()<desiredlength){
s+=" ";
}
return s;
}
public String truncString(String s, int desiredlength){
return s.substr(0,s.length()-desiredlenght);
}
错误:
我根据我在代码的另一部分中测试的字符串长度来应用这两个:
[...]//here i built my class
int maxlen = 60;
[...] //here there is more code but it just collects data and I already tested fields
if (field.length()<maxlen){
field = formatSpace(field,maxlen);
}else if (field.length()>maxlen){
field = truncString(field,maxlen);
}
[...] //here i put string on file
我得到的错误是关于字符串索引是否定的,我不知道为什么,我在纸上尝试了代码(是的,我知道它是愚蠢的)但它在那里工作
为什么第二个功能不起作用? 另外,最好制作一个格式化我的字符串的函数,我该怎么做呢?
解决方案:
感谢所有评论过的人,我用我编写的这个单一功能解决了我的问题,我甚至不再测试字符串,如果它们符合我的长度,他们就可以了,否则我将它们格式化:
private String formatString(String s, int length) {
while (s.length() < length) {
s += " ";
}
return s.substring(0, length);
}
答案 0 :(得分:1)
substring
函数中的第二个参数是新String的长度。为什么你有减法?
这应该有效:
public String truncString(String s, int desiredlength){
return s.substr(0,desiredlenght);
}
答案 1 :(得分:0)
第二个功能中的问题是逻辑问题。想象一下,你想要的长度是4,你引入一个长度为6的字符串。如果你做了字符串长度 - 所需的长度,你将获得一个长度为2的字符串。
解决此问题的方法是直接返回substr:return s.substr(0,desiredLenght)
答案 2 :(得分:0)
或者您可以尝试这种方法来获得简单的单行解决方案。
String test="type something here";
int desiredLength=15;
System.out.println(String.format("%1$-"+desiredLength+"s", test.substring(0, desiredLength)));
这个想法是=&gt; substring首先到达所需的长度(如果string更长,则会发生这种情况),然后使用String格式用空格填充所需的长度(%1 $ -10s是左对齐字符串填充到10个空格的格式)。
答案 3 :(得分:0)
你有一个错字。在truncString里面你可以写出desiredlenght而不是所需的长度。
答案 4 :(得分:0)
我通常使用类似的东西:
private static String spaces(int width) {
// May be more efficient ways of doing this.
return String.join("", Collections.nCopies(width, " "));
}
private static String fixedWidth(String s, int width, boolean padLeft) {
String spaces = spaces(Math.max(0,width-s.length()));
return (padLeft ? spaces + s : s + spaces).substring(0, width);
}
public void test(String[] args) {
String[] tests = {"Hello", "Loooooooooooooong!!!"};
for ( String t: tests) {
System.out.println(fixedWidth(t,10,false));
System.out.println(fixedWidth(t,10,true));
}
}