這是最近參加的一個公司的筆試題,回家上機寫了下代碼,但願對有須要的小夥伴有用,簡單實現字符串和數組在指定位置的插入:數組
package org.flhs;this
import com.google.common.base.Strings;google
/**
* Created with IntelliJ IDEA.
* User: cutter.li
* Date: 14-3-7
* Time: 下午3:10
* To change this template use File | Settings | File Templates.
*/
public class FLHSTest {spa
public static void main(String[] args) {rem
// changePosition("iloveyou", 5);字符串
Object[] objArray= insertObjArrayInPosition(new Object[]{"a","b","hello"},new Object[]{"fuck","you"},3);string
printArray(objArray);it
}io
private static void printArray(Object[] objArray) {
if(null!=objArray&&objArray.length>0)
{
for(Object obj:objArray)
{
System.out.print(obj+" , ");
}
}
}class
//對指定位置先後的字符串的內容進行調換
public static void changePosition(String str, int position) {
String res = "";
if (Strings.isNullOrEmpty(str)) {
res = "改變的字符串爲空";
} else {
int len = str.length();
if (position <= 0 || position >= len) {
res = str;
} else {
String preTxt = str.substring(0, position);
String remainTxt = str.substring(position, str.length());
res = remainTxt + preTxt;
}
}
System.out.println(res);
}
//數組在指定位置的插入
public static Object[] insertObjArrayInPosition(Object[] dest, Object[] source, int position) {
if (null == dest) {
return source;
}
if (null == source) {
return dest;
}
int destSize = dest.length;
int sourceSize = source.length;
Object[] resObjArray = new Object[destSize + sourceSize];
if (position <= 0) {
System.arraycopy(source, 0, resObjArray, 0, sourceSize);
System.arraycopy(dest , 0, resObjArray, sourceSize, destSize);
} else if (position > dest.length) {
System.arraycopy(dest, 0, resObjArray, 0, destSize);
System.arraycopy(source, 0, resObjArray, destSize, sourceSize);
} else {
System.arraycopy(dest, 0, resObjArray, 0, position);
System.arraycopy(source, 0, resObjArray, position, sourceSize);
System.arraycopy(dest, position, resObjArray, position+sourceSize, destSize - position);
}
return resObjArray;
}
}