如何从推算的字符串中交换2个估算的章程?

时间:2017-10-02 23:53:12

标签: java

如何创建一个程序,输入一个句子,然后输入两个字母,然后切换这些字母的所有实例,然后打印出切换的句子。例如,如果这个人输入“我喜欢吃香蕉”,然后输入“e”和“a”,那么你的程序就会打印出“I lika to aet benenes"。

到目前为止,我已经有了这段代码,但是我很困难,并且不太了解转换为数组或字符串构建器。我知道这是不兼容的类型,但我只想表明我正在尝试,这是我的想法到目前为止基于研究。

import java.util.*;

public class StringLetterSwitcher
{
public static void main(String [] arga)
{
   System.out.println("Enter your string");
   Scanner scan = new Scanner(System.in);

   String originalString = scan.nextLine();

   System.out.println("What 2 letters would you like to swap?");
   String letter1 = scan.nextLine();
   String letter2 = scan.nextLine();

     char[] c = originalString.toCharArray();

     char temp = c[letter1];
     c[letter1] = c[letter2];
     c[letter2] = temp;

    String swappedString = new String(c);
    System.out.println(swappedString);
}

}

1 个答案:

答案 0 :(得分:0)

我使用String.replace()将letter1替换为letter2,然后在originalString中找到letter2的索引,用letter1替换letter2(注意char [] c是newString,而不是originalString)。

public static void main(String[] args) {
    System.out.println("Enter your string");
    Scanner scan = new Scanner(System.in);

    String originalString = scan.nextLine();

    System.out.println("What 2 letters would you like to swap?");
    String letter1 = scan.nextLine();
    String letter2 = scan.nextLine();

    String newString = originalString.replace(letter1, letter2);        //replaced letter1 with letter2
    char[] c = newString.toCharArray();

    for(int i=0; i<originalString.length(); i++) {
        if (originalString.charAt(i) == letter2.charAt(0)) {            //if char in originalString == letter2
            c[i] = letter1.charAt(0);                                   //replaced letter2 with letter1
        }       
    }
    System.out.println(c);
}