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+ch
外if
声明,不确定您是否故意这样做:
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/