我試圖做一個程序,可以前後串然後要求用戶添加一個新的字符串並打印新的字符串,用戶喜歡這裏是一個樣本的位置後讀取字符串:如何在字符串前後打印字符串然後將新字符串添加到舊字符串中?
Enter a long string: The quick brown fox jumped over the lazy dog Enter a substring: jumped Length of your string: 44 Length of your substring: 6 Starting position of your substring in string: 20 String before your substring: The quick brown fox String after your substring: over the lazy dog Enter a position between 0 and 43: 18 The character at position 18 is x Enter a replacement string: leaped Your new string is: The quick brown fox leaped over the lazy dog
這裏是我的代碼,我在做什麼:
import java.util.Scanner;
public class Project02 {
public static void main(String[] args) {
Scanner name = new Scanner (System.in);
System.out.println("Enter a long string: ");
String username = name.nextLine();
System.out.println("Enter a substring: ");
String subname = name.nextLine();
System.out.println("Length of your string: "+ username.length());
System.out.println("Length of your substring: " + subname.length());
System.out.println("Starting position of your substring in string: "+ username.indexOf(subname));
System.out.println("Enter a replacement string: ");
String newname = name.nextLine();
System.out.println("Your new string is: "+);
}
}
當我添加一個新的字符串之間的這些字符串用戶子字符串是刪除這裏是我添加的代碼:'System.out.println(「Enter a replacement string:」); \t \t String newname = name.nextLine(); (「你的新字符串是:」+ username.substring(0,username.indexOf(subname))+「」+ newname +「」+ username.substring(username.indexOf(subname)+ subname(012) 。長度())); \t \t' – bscouth 2014-09-13 03:35:39
是的,應該這樣做。儘管您不需要在每個組件字符串之間添加空格。 – jackarms 2014-09-13 03:50:35
這是它看起來像http://i58.tinypic.com/28gryv8.png 當它打印新的字符串時,它刪除舊的字符串 – bscouth 2014-09-13 03:55:28