gpt4 book ai didi

java - 如何在子字符串之前和之后打印字符串,然后将新字符串添加到旧字符串中?

转载 作者:行者123 更新时间:2023-12-01 12:32:41 24 4
gpt4 key购买 nike

我正在尝试制作一个程序,可以读取子字符串之前和之后的字符串,然后要求用户添加新字符串并打印新字符串,用户喜欢的位置是一个示例:

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: "+ );


}

}

最佳答案

所以:

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;

关于java - 如何在子字符串之前和之后打印字符串,然后将新字符串添加到旧字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25819377/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com