私はこれらすべてにまったく慣れていないので、ユーザーがテキストを入力して (文字列として保存)、コードで単語の位置を検索し、置換して、ひもを再び結合します。すなわち:
「ランチはフーが好き」
foo は 7 番目の位置にあります
新しい入力: I like Foo for lunch
これが私がこれまでに持っているものです:
import java.util.Scanner;
public class FooExample
{
public static void main(String[] args)
{
/** Create a scanner to read the input from the keyboard */
Scanner sc = new Scanner (System.in);
System.out.println("Enter a line of text with foo: ");
String input = sc.nextLine();
System.out.println();
System.out.println("The string read is: " + input);
/** Use indexOf() to position of 'foo' */
int position = input.indexOf("foo");
System.out.println("Found \'foo\' at pos: " + position);
/** Replace 'foo' with 'Foo' and print the string */
input = input.substring(0, position) + "Foo";
System.out.println("The new sentence is: " + input);
問題は最後に発生しています-文の残りの部分を連結に追加する方法に困惑しています:
input = input.substring(0, position) + "Foo";
単語を置き換えることはできますが、残りの文字列を取り付ける方法について頭を悩ませています。