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

我要进入一个6位数值的 int。我想将它显示为带有小数点(.)的 Stringint结尾处的2位。我想使用一个 float,但有人建议使用 String为一个更好的显示输出(而不是 1234.5将是 1234.50)。因此,我需要一个函数,将采取一个 int作为参数,并返回正确格式的 String与小数点2位从结束。

说:

int j= 123456
Integer.toString(j);


//processing...


//output : 1234.56
474097 次浏览
int j = 123456;
String x = Integer.toString(j);
x = x.substring(0, 4) + "." + x.substring(4, x.length());
int yourInteger = 123450;
String s = String.format("%6.2f", yourInteger / 100.0);
System.out.println(s);

你可以用

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

根据注释,12345/100.0会更好,使用 double 代替 float 也会更好。

如果你正在使用一个浮点数很昂贵的系统(例如没有 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可能比使用 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();
  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;
}

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

我认为在特定位置插入 String 的一个更简单、更优雅的解决方案是这样的一行程序:

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

例如,要在时间字符串中插入缺失的 ::

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

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

当然,它没有 StringBuilder 解决方案那样的性能,但是我相信简洁和优雅作为一个简单易读的一行程序(相对于一个庞大的方法)足以使它成为大多数非性能关键用例的首选解决方案。

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

// 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());

试试这个:

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

使用 ApacheCommons 3 StringUtils,您也可以这样做

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


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

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

格式(“% 0d.% 02d”,d/100,d% 100) ;

对于 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")

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

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

结果 = 24/08

这个示例显示了卡的有效期,斜杠(/)应该在第2索引处。所以在这种情况下生成的索引将有/at 第2个索引。

如果要替换而不是添加:

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

结果 = 24/0