我有如下代码
String singlestr="hello|world|how|are|you";
String[] arraystr = singlestr.split("|");
结果我有=>
arraystr[0]=hello
arraystr[1]=world
arraystr[2]=how
arraystr[3]=are
arraystr[4]=you
现在的问题是如何将新字符串插入到第三个位置?有什么功能吗?
将新字符串插入索引 2 后的预期输出:
arraystr[0]=hello
arraystr[1]=world
arraystr[2]=hi
arraystr[3]=how
arraystr[4]=are
arraystr[5]=you
最佳答案
尝试使用 StringBuilder。使用append() 方法插入arrayStr 中的元素,然后使用insert() 在所需位置插入新文本。 toString() 方法将返回完成的字符串。
我的示例代码假设您知道新文本的确切插入点。更通用的方法是使用 indexOf() 方法来获取插入点后面的文本的偏移量,然后使用该索引作为调用 insert() 时的偏移量参数。此外,您的示例将初始字符串拆分为不带嵌入分隔符的单独单词。 toString() 将返回“helloworldhihowareyou”。如果您希望在结果字符串中分隔单词,请在将其添加到 StringBuilder 对象之前向 arrayStr 的每个元素附加一个空格字符(或其他分隔符?)。
String singlestr="hello|world|how|are|you";
String[] arraystr = singlestr.split("|");
StringBuilder builder = new StringBuilder ();
String newString;
for (String s: arraystr) {
builder.append(s.concat(" ")); // Add with separator
}
builder.insert(10,"hi");
newString = builder.toString();
关于java - 如何将字符串插入到字符串数组中的特定索引并在之后移动字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38359287/