有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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


    }

}

共 (2) 个答案

  1. # 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;
    
  2. # 2 楼答案

    输入的子字符串前面的字符串应该是username.substring(0, username.indexOf(subname),然后后面的字符串应该是username.substring(username.indexOf(subname) + subname.length)。然后在这两个子字符串之间打印新字符串