java - 我编写了这段代码,用于从字符串中删除特定单词

标签 java string class loops

class abc
{
    void main(String s)
    {
        s=s+" ";
        String st="";String sen="";
        int l=s.length();
        char ch;
        for(int i=0;i<l-1;i++)
        {
            ch=s.charAt(i);
           if (ch!=' ')
           {
               st=st+ch;

        }
        else
        {
            if(st.equalsIgnoreCase("The"))
            {
                sen=sen+" "+st;
                st="";
            }
        }
    }
       System.out.println("The new string is"+st);
    }
}

我正在尝试从字符串中删除单词“The”。

输入: s =“大猫”

预期输出: “大猫”

实际输出: “大卡”

最佳答案

更改了一些 for 循环代码:

    for(int i=0;i<=l-1;i++)
    {
        ch=s.charAt(i);
        st=st+ch;
        if(st.equalsIgnoreCase("The"))
        {
            sen=sen+" "+st;
            st="";
        }
    }
    System.out.println("The new string is: "+st);

有两件事:

1) for 循环需要循环直到输入字符串的最后一个字符( i<=l-1 而不是 i<l-1 )

2) 下面的代码删除了空格并将单词连接在一起,所以我移出了 st=st+chif声明,不确定您是否故意这样做:

if (ch!=' ')
{
    st=st+ch;

}

完整代码和输入:

public static void main(String[] args) {
    String s="the big cat is the best";
    String st="";
    String sen="";
    int l=s.length();
    char ch;
    for(int i=0;i<=l-1;i++)
    {
        ch=s.charAt(i);
        st=st+ch;
        if(st.equalsIgnoreCase("The"))
        {
            sen=sen+" "+st;
            st="";
        }
    }
    System.out.println("The new string is: "+st);
}

输出:

The new string is: big cat is the best

关于java - 我编写了这段代码,用于从字符串中删除特定单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40489518/

相关文章:

c - 我的代码中是否存在内存泄漏? (使用指针存储字符串)

javascript - 如何选择字符串的最后两个字符

class - 将 propTypes 和 defaultProps 作为静态 props 放入 React 类中可以吗?

C#-调用覆盖版本的方法的基本版本

java - 使用 Java 8 流对象将列表对象转换为自定义映射

java - 将数据从 SOAP 处理程序传递到 Web 服务服务器类

java - java 中月份结束的星期几的名称和开始日期的名称

java - 外部 Jar 不工作 "Could not autowire"

c++ - 流不按预期工作

java - 如何使用泛型(java)在编译时检测类差异