【问题标题】:Replacing a particular word in a scanned in string and concatenating using substring() in Java替换扫描字符串中的特定单词并在 Java 中使用 substring() 进行连接
【发布时间】:2013-01-29 12:46:31
【问题描述】:

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

'我喜欢吃午饭'

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

我可以得到要替换的单词,但我正在为如何让其余的字符串附加上而摸不着头脑。

【问题讨论】:

  • 也许你应该从“foo”之后的位置开始子串?

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


【解决方案1】:
input = input.substring(0,position) + "Foo" + input.substring(position+3 , input.length());

或者干脆你可以使用替换方法。

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 澄清一下,+3 表示第二个子字符串跳过了原来的“foo”(长度为 3)。
    • 掌心我会记住的!最简单的事情让我措手不及!谢谢!
    【解决方案3】:

    这可能有点矫枉过正,但如果您正在寻找句子中的单词,您可以轻松使用 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;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-03
      • 2016-11-08
      • 2012-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-13
      相关资源
      最近更新 更多