java 在特定位置附加到字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14453438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:19:05  来源:igfitidea点击:

Append to String at certain position

java

提问by maddy

I have a String miscFlag which is of size 100. I need to append to this miscFlag starting from index 20 as 0-19 are reserved for some other info. And then append subsequently at certain positions only. Can we do this using StringBuilder/StringBuffer?

我有一个大小为 100 的 String miscFlag。我需要从索引 20 开始附加到这个 miscFlag,因为 0-19 是为其他一些信息保留的。然后仅在某些位置随后附加。我们可以使用 StringBuilder/StringBuffer 来做到这一点吗?

This is how i am trying to do it..

这就是我正在尝试这样做的方式..

    StringBuilder info = new StringBuilder(miscFlag);
    info.append(" ");
    info.append(Misc.toTimestampLiteral(currentDate));//append this from pos 20
    info.append(" ");
    info.append(formattedStartTime);  //append this from pos 40

Here i am not able to specify the position from where to append.

在这里我无法指定从哪里追加的位置。

回答by Farmor

Use the insert method.

使用插入方法。

info.insert(19, Misc.toTimestampLiteral(currentDate));

回答by Subhrajyoti Majumder

Use String#subStringto cut 0 to 20 index and then add new String.

使用String#subString削减0至20索引,然后添加新的字符串。

String str = miscFlag.substring(0,20)+ " "+Misc.toTimestampLiteral(currentDate)+" "+  miscFlag.substring(21);

回答by Audrius Meskauskas

Fixed length fields are doable with StringBuilderbut looks for me very clumsy and error-prone, I would not recommend. Use String.format, it is exactly for that you need - to create string where field widths and positions are important:

固定长度字段是可行的,StringBuilder但看起来我很笨拙且容易出错,我不推荐。使用String.format,它正是您需要的 - 创建字段宽度和位置很重要的字符串:

 String.format("A[%8s][%4s]", "ab","cd");

will result

将导致

 A[      ab][  cd]

回答by Chaitanya K

You can specify the sposition where you'd like to insert as below

您可以指定要插入的位置,如下所示

StringBuilder info = new StringBuilder(miscFlag);
info.insert(19, Misc.toTimestampLiteral(currentDate) + " ");
info.insert(39, formattedStartTime + " ");