在特定位置的字符串中插入字符

时间:2011-05-04 13:42:47

标签: java string casting

我正在使用一个6位数的int。我希望将其显示为String,其小数点(。)位于int末尾的2位数字处。我想使用float但建议使用String来获得更好的显示输出(而不是1234.5将是1234.50)。因此,我需要一个函数,它将int作为参数并返回格式正确的String,其末尾有小数点2位数。

说:

int j= 123456 
Integer.toString(j); 

//processing...

//output : 1234.56

13 个答案:

答案 0 :(得分:191)

正如评论中所提到的,StringBuilder可能是一个更快的实现,然后使用StringBuffer。正如Java文档中提到的那样:

  

此类提供与StringBuffer兼容的API,但不保证同步。此类设计用作StringBuffer的替代品,用于单个线程使用字符串缓冲区的位置(通常情况下)。在可能的情况下,建议首先使用此类优先于StringBuffer,因为在大多数实现中它会更快。

用法:

String str = Integer.toString(j);
str = new StringBuilder(str).insert(str.length()-2, ".").toString();

或者,如果您需要同步,请使用具有类似用法的StringBuffer

String str = Integer.toString(j);
str = new StringBuffer(str).insert(str.length()-2, ".").toString();

答案 1 :(得分:171)

int j = 123456;
String x = Integer.toString(j);
x = x.substring(0, 4) + "." + x.substring(4, x.length());

答案 2 :(得分:16)

int yourInteger = 123450;
String s = String.format("%6.2f", yourInteger / 100.0);
System.out.println(s);

答案 3 :(得分:4)

在大多数用例中,使用StringBuilder(已经回答过)是一种很好的方法。但是,如果性能很重要,这可能是一个很好的选择。

/**
 * Insert the 'insert' String at the index 'position' into the 'target' String.
 * 
 * ````
 * insertAt("AC", 0, "") -> "AC"
 * insertAt("AC", 1, "xxx") -> "AxxxC"
 * insertAt("AB", 2, "C") -> "ABC
 * ````
 */
public static String insertAt(final String target, final int position, final String insert) {
    final int targetLen = target.length();
    if (position < 0 || position > targetLen) {
        throw new IllegalArgumentException("position=" + position);
    }
    if (insert.isEmpty()) {
        return target;
    }
    if (position == 0) {
        return insert.concat(target);
    } else if (position == targetLen) {
        return target.concat(insert);
    }
    final int insertLen = insert.length();
    final char[] buffer = new char[targetLen + insertLen];
    target.getChars(0, position, buffer, 0);
    insert.getChars(0, insertLen, buffer, position);
    target.getChars(position, targetLen, buffer, position + insertLen);
    return new String(buffer);
}

答案 4 :(得分:3)

您可以使用

System.out.printf("%4.2f%n", ((float)12345)/100));

根据评论,12345 / 100.0会更好,使用double而不是float。

答案 5 :(得分:0)

如果您使用浮动价格昂贵的系统(例如没有FPU)或不允许(例如在会计中),您可以使用以下内容:

    for (int i = 1; i < 100000; i *= 2) {
        String s = "00" + i;
        System.out.println(s.substring(Math.min(2, s.length() - 2), s.length() - 2) + "." + s.substring(s.length() - 2));
    }

否则DecimalFormat是更好的解决方案。 (上面的StringBuilder变体不适用于小数字(&lt; 100)

答案 6 :(得分:0)

  public static void main(String[] args) {
    char ch='m';
    String str="Hello",k=String.valueOf(ch),b,c;

    System.out.println(str);

    int index=3;
    b=str.substring(0,index-1 );
    c=str.substring(index-1,str.length());
    str=b+k+c;
}

答案 7 :(得分:0)

clientTeamId

答案 8 :(得分:0)

尝试一下:

public String ConvertMessage(String content_sendout){

        //use unicode (004E00650077) need to change to hex (&#x004E&#x;0065&#x;0077;) first ;
        String resultcontent_sendout = "";
        int i = 4;
        int lengthwelcomemsg = content_sendout.length()/i;
        for(int nadd=0;nadd<lengthwelcomemsg;nadd++){
            if(nadd == 0){
                resultcontent_sendout = "&#x"+content_sendout.substring(nadd*i, (nadd*i)+i) + ";&#x";
            }else if(nadd == lengthwelcomemsg-1){
                resultcontent_sendout += content_sendout.substring(nadd*i, (nadd*i)+i) + ";";
            }else{
                resultcontent_sendout += content_sendout.substring(nadd*i, (nadd*i)+i) + ";&#x";
            }
        }
        return resultcontent_sendout;
    }

答案 9 :(得分:0)

使用ApacheCommons3 StringUtils,您也可以这样做

int j = 123456;
String s = Integer.toString(j);
int pos = s.length()-2;

s = StringUtils.overlay(s,".", pos, pos);

它基本上是子字符串连接,但是如果您不介意使用库,或者已经依赖StringUtils,则可以缩短

答案 10 :(得分:0)

String.format(“%0d。%02d”,d / 100,d%100);

答案 11 :(得分:0)

对于Kotlin帅哥;)从已接受的答案(@ MikeThomsen's)中

fun String.insert(index: Int, string: String): String {
    return this.substring(0, index) + string + this.substring(index, this.length)
}

测试✅

"ThisTest".insert(4, "Is").should.equal("ThisIsTest")

答案 12 :(得分:-1)

我认为在一个特定的位置插入一个更简单,更优雅的解决方案就是这个单行:

target.replaceAll("^(.{" + position + "})", "$1" + insert);

例如,要将缺少的:插入时间字符串:

"-0300".replaceAll("^(.{3})", "$1:");

它的作用是,匹配字符串开头的position个字符,对这些字符进行分组,并将该组替换为自身($1),后跟insert字符串。注意replaceAll,即使总是出现一次,因为第一个参数必须是正则表达式。

当然它与StringBuilder解决方案没有相同的性能,但我相信简洁和优雅是一个简单易读的单线程(与一个巨大的方法相比)足以使其成为首选的解决方案大多数非性能关键用例。

注意我出于文档原因解决了标题中的一般性问题,当然如果您要处理十进制数,则应使用已经提出的特定于域的解决方案。

相关问题