0

私はこれらすべてにまったく慣れていないので、ユーザーがテキストを入力して (文字列として保存)、コードで単語の位置を検索し、置換して、ひもを再び結合します。すなわち:

「ランチはフーが好き」

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";

単語を置き換えることはできますが、残りの文字列を取り付ける方法について頭を悩ませています。

4

3 に答える 3

1
input = input.substring(0,position) + "Foo" + input.substring(position+3 , input.length());

または単に replace メソッドを使用できます。

input = input.replace("foo", "Foo");
于 2013-01-29T12:50:15.270 に答える
0

「foo」を再度含めたくないことを考慮して、Achintyaが投稿したものを少し更新します。

input = input.substring(0, position) + "Foo" + input.substring(position + 3 , input.length());
于 2013-01-29T12:52:52.493 に答える
0

これはやり過ぎかもしれませんが、文中の単語を探している場合は、StringTokenizer を簡単に使用できます。

            StringTokenizer st = new StringTokenizer(input);
            String output="";
            String temp = "";
            while (st.hasMoreElements()) {
               temp = st.nextElement();
        if(temp.equals("foo"))
                       output+=" "+"Foo";
                    else
                       output +=" "+temp;
    }
于 2013-01-29T12:55:20.470 に答える