我正在尝试创建一个程序,可以读取子字符串之前和之后的字符串然后要求用户添加一个新字符串并打印新字符串,用户喜欢这里的位置是样本:
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: "+ );
}
}
答案 0 :(得分:1)
所以:
int index = text.indexOf(substring);
String left = text.substring(0, index);
String right = text.substring(index + substring.length());
String replacement = name.nextLine();
String newText = left + replacement + right;
答案 1 :(得分:0)
输入的子字符串之前的字符串应该只是username.substring(0, username.indexOf(subname)
,然后后面的字符串应该只是username.substring(username.indexOf(subname) + subname.length)
。然后只需在这两个子串之间打印新字符串。