如何在字符串中的某个位置插入一个字符?

发布于 2024-11-05 04:56:16 字数 413 浏览 2 评论 0原文

我收到一个带有 6 位数字值的 int 。我想将其显示为 String,在距 int 末尾 2 位处有一个小数点 (.)。我想使用 float 但建议使用 String 以获得更好的显示输出(而不是 1234.5 将是 1234.50代码>)。因此,我需要一个函数,它将接受 int 作为参数,并返回格式正确的 String ,小数点距末尾 2 位。

说:

int j= 123456 
Integer.toString(j); 

//processing...

//output : 1234.56

I'm getting in an int with a 6 digit value. I want to display it as a String with a decimal point (.) at 2 digits from the end of int. I wanted to use a float but was suggested to use String for a better display output (instead of 1234.5 will be 1234.50). Therefore, I need a function that will take an int as parameter and return the properly formatted String with a decimal point 2 digits from the end.

Say:

int j= 123456 
Integer.toString(j); 

//processing...

//output : 1234.56

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

一抹苦笑 2024-11-12 04:56:16

正如评论中提到的, 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();

As mentioned in comments, a StringBuilder is probably a faster implementation than using a StringBuffer. As mentioned in the Java docs:

This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

Usage :

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

Or if you need synchronization use the StringBuffer with similar usage :

String str = Integer.toString(j);
str = new StringBuffer(str).insert(str.length()-2, ".").toString();
白龙吟 2024-11-12 04:56:16
int j = 123456;
String x = Integer.toString(j);
x = x.substring(0, 4) + "." + x.substring(4, x.length());
int j = 123456;
String x = Integer.toString(j);
x = x.substring(0, 4) + "." + x.substring(4, x.length());
寂寞笑我太脆弱 2024-11-12 04:56:16
int yourInteger = 123450;
String s = String.format("%6.2f", yourInteger / 100.0);
System.out.println(s);
int yourInteger = 123450;
String s = String.format("%6.2f", yourInteger / 100.0);
System.out.println(s);
就像说晚安 2024-11-12 04:56:16

使用 ApacheCommons3 StringUtils,你也可以做

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

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

它基本上是子字符串连接,但如果你不介意使用库,或者已经依赖于 StringUtils,那么它会更短

Using ApacheCommons3 StringUtils, you could also do

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

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

it's basically substring concatenation but shorter if you don't mind using libraries, or already depending on StringUtils

嘿看小鸭子会跑 2024-11-12 04:56:16

在大多数用例中,使用 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);
}

In most use-cases, using a StringBuilder (as already answered) is a good way to do this. However, if performance matters, this may be a good alternative.

/**
 * 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);
}
水晶透心 2024-11-12 04:56:16

对于 Kotlin 伙计们;)来自已接受的答案(@MikeThomsen 的)

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

测试 ✅

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

For Kotlin dudes ;) from the accepted answer (@MikeThomsen's)

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

Test ✅

"ThisTest".insert(insertAt = 4, string = "Is").should.equal("ThisIsTest")
魔法少女 2024-11-12 04:56:16

String.format("%0d.%02d", d / 100, d % 100);

String.format("%0d.%02d", d / 100, d % 100);

半步萧音过轻尘 2024-11-12 04:56:16

您可以使用

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

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

You could use

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

As per the comments, 12345/100.0 would be better, as would the use of double instead of float.

喵星人汪星人 2024-11-12 04:56:16

如果您使用的系统中浮点值昂贵(例如没有 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 变体不适用于小数字(<100)

If you are using a system where float is expensive (e.g. no FPU) or not allowed (e.g. in accounting) you could use something like this:

    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));
    }

Otherwise the DecimalFormat is the better solution. (the StringBuilder variant above won't work with small numbers (<100)

薄荷→糖丶微凉 2024-11-12 04:56:16

我认为在某个位置插入字符串的一种更简单、更优雅的解决方案是这样的:

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

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

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

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

当然,它没有与 StringBuilder 解决方案相同的性能,但我相信作为一种简单且易于阅读的单行(与庞大的方法相比)的简洁和优雅足以使其成为大多数非性能的首选解决方案-关键用例。

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

I think a simpler and more elegant solution to insert a String in a certain position would be this one-liner:

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

For example, to insert a missing : into a time String:

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

What it does is, matches position characters from the beginning of the string, groups that, and replaces the group with itself ($1) followed by the insert string. Mind the replaceAll, even though there's always one occurrence, because the first parameter must be a regex.

Of course it does not have the same performance as the StringBuilder solution, but I believe the succinctness and elegance as a simple and easier to read one-liner (compared to a huge method) is sufficient for making it the preferred solution in most non performance-critical use-cases.

Note I'm solving the generic problem in the title for documentation reasons, of course if you are dealing with decimal numbers you should use the domain-specific solutions already proposed.

知足的幸福 2024-11-12 04:56:16
  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;
}
  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;
}
人海汹涌 2024-11-12 04:56:16
// Create given String and make with size 30
String str = "Hello How Are You";

// Creating StringBuffer Object for right padding
StringBuffer stringBufferRightPad = new StringBuffer(str);
while (stringBufferRightPad.length() < 30) {
    stringBufferRightPad.insert(stringBufferRightPad.length(), "*");
}

System.out.println("after Left padding : " + stringBufferRightPad);
System.out.println("after Left padding : " + stringBufferRightPad.toString());

// Creating StringBuffer Object for right padding
StringBuffer stringBufferLeftPad = new StringBuffer(str);
while (stringBufferLeftPad.length() < 30) {
    stringBufferLeftPad.insert(0, "*");
}
System.out.println("after Left padding : " + stringBufferLeftPad);
System.out.println("after Left padding : " + stringBufferLeftPad.toString());
// Create given String and make with size 30
String str = "Hello How Are You";

// Creating StringBuffer Object for right padding
StringBuffer stringBufferRightPad = new StringBuffer(str);
while (stringBufferRightPad.length() < 30) {
    stringBufferRightPad.insert(stringBufferRightPad.length(), "*");
}

System.out.println("after Left padding : " + stringBufferRightPad);
System.out.println("after Left padding : " + stringBufferRightPad.toString());

// Creating StringBuffer Object for right padding
StringBuffer stringBufferLeftPad = new StringBuffer(str);
while (stringBufferLeftPad.length() < 30) {
    stringBufferLeftPad.insert(0, "*");
}
System.out.println("after Left padding : " + stringBufferLeftPad);
System.out.println("after Left padding : " + stringBufferLeftPad.toString());
小女人ら 2024-11-12 04:56:16

这里有很好的答案,但是通过添加 Kotlin 扩展,我们可以做得更简单:

    val indexWhereInsertIsIntended = 2
    val inputString = "2408"
    val resultingString = inputString.toCharArray().toMutableList()
        .also { 
             it.add(indexWhereInsertIsIntended, '/') 
        }.joinToString("")

结果 = 24/08

此示例显示卡到期日期,斜线 (/) 用于第二个索引。因此,在这种情况下生成的索引将在第二个索引处具有 / 。

如果您想替换而不添加:

val indexWhereInsertIsIntended = 2
        val inputString = "2408"
        val resultingString = inputString.toCharArray()
            .also { 
                 it[indexWhereInsertIsIntended] = '/' 
            }.joinToString("")

结果 = 24/0

There are good answers here, but with Kotlin extensions addition we can do it even more simply:

    val indexWhereInsertIsIntended = 2
    val inputString = "2408"
    val resultingString = inputString.toCharArray().toMutableList()
        .also { 
             it.add(indexWhereInsertIsIntended, '/') 
        }.joinToString("")

Result = 24/08

This example shows a card expiry date, and slash (/) is intended at 2nd Index. So the resulting index in this case will have / at 2nd index.

If you want to replace and not add:

val indexWhereInsertIsIntended = 2
        val inputString = "2408"
        val resultingString = inputString.toCharArray()
            .also { 
                 it[indexWhereInsertIsIntended] = '/' 
            }.joinToString("")

Result = 24/0

ぶ宁プ宁ぶ 2024-11-12 04:56:16

试试这个:

public String ConvertMessage(String content_sendout){

        //use unicode (004E00650077) need to change to hex (N&#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;
    }

Try this :

public String ConvertMessage(String content_sendout){

        //use unicode (004E00650077) need to change to hex (N&#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;
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文