替换扫描的字符串中的特定单词并使用Java中的substring()进行连接

时间:2013-01-29 12:46:31

标签: java substring java.util.scanner string-concatenation

我对这一切都是全新的,所以我试着编写一段简单的代码,允许用户输入文本(保存为字符串),然后让代码搜索单词的位置,替换它并将字符串重新连接在一起。即:

'我喜欢foo吃午饭'

foo位于第7位

新的输入是:我喜欢Foo吃午饭

这是我到目前为止所做的:

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

我可以让这个词被替换,但我正在摸索如何连接其余的字符串。

3 个答案:

答案 0 :(得分:1)

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

或者只是你可以使用替换方法。

input = input.replace("foo", "Foo");

答案 1 :(得分:0)

轻微更新Achintya发布的内容,考虑到您不想再次包含“foo”:

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

答案 2 :(得分: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;
    }