给定数组String[] names = new String[]{"Jim","Tony"};请写出在"Tony"之前插入"Tom"得到新数组的代码

2024-12-14 07:22:14
推荐回答(3个)
回答1:

没用到arraycopy,自己写了个函数 public string[] getnew(string add, string wei, string[] shu)
{
bool falg = false;
string[] newstring = new string[shu.Length + 1];
for (int i = 0; i <=shu.Length; i++)
{
if (i < shu.Length)
{
if (shu[i] == wei)
{
falg = true;
newstring[i] = add;
}
else
{
if (!falg)
newstring[i] = shu[i];
else
{
newstring[i] = shu[i - 1];
}
}
}
else
{
newstring[shu.Length] = shu[shu.Length - 1];
}
}
return newstring; }add为你要加入的字符,wei为你要插入字符的前一个字符,比如你题目里的Tony,shu为你未插入之前的数组

回答2:

import java.util.*;

class test
{
public static void main(String[] args)
{
String[] names = new String[]{"Jim","Tony"};
String[] t = new String[names.length+1];
System.arraycopy(names, 0, t, 0, 1);
System.arraycopy(new String[]{"Tom"}, 0, t, 1, 1);
System.arraycopy(names, 1, t, 2, 1);
for(String s:t)
System.out.println(s);
}
}

回答3:

string[] names = new string[] {"Jim","Tony"};
string[] x = new string[3];
Array.Copy(names, 0, x, 0, 1);
x[1] = "Tom";
Array.Copy(names, 1, x, 2, 1);
foreach (string y in x)
{
MessageBox.Show(y);
}