問題 E: 將字符串插入到另一個字符串的指定位置(串)
時間限制: 1 Sec 內存限制: 128 MB
提交: 2018 解決: 1277
[提交] [狀態] [命題人:外部導入]
題目描述
將字符串t插入到字符串s中,在位置pos後插入。不得使用字符串操作函數,輸出組合成的字符串。
輸入
輸入兩個字符串(t和s)和要插入的位置(pos)
輸出
輸出組合後的字符串
樣例輸入 Copy
qwe jij 3
樣例輸出 Copy
jijqwe
解法1:
import java.util.Scanner;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
String str = scan.next();
String tmp = scan.next();
int f = scan.nextInt();
if(f!=tmp.length()){
for(int i=0;i<tmp.length();i++){
if(i==f){
System.out.printf("%s", str);
}
System.out.printf("%c", tmp.charAt(i));
}
}else{
System.out.printf(tmp);
System.out.printf(str);
}
System.out.println();
}
}
解法2:常規解法,StringBuffer。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO 自動生成的方法存根
Scanner scan = new Scanner(System.in);
//int n = scan.nextInt();
String temp = scan.nextLine();
String later = scan.next();
int n = scan.nextInt();
StringBuffer sb = new StringBuffer();
sb.append(later);
sb.insert(n,temp);
System.out.println(sb);
}
}