[英]Program to remove a word from a sentence
如何在不使用單詞編號選項的情況下修改程序? 請給我一個簡化的程序。
要使該程序在沒有單詞編號的情況下應該怎么做?
import java.io.*;
class Sentence
{
public static void main(String ar[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the sentence");
StringBuffer sentence=new StringBuffer(br.readLine()+" ");
System.out.println("Enter the word to be deleted");
String word=br.readLine();
int n=0;
int wordno;
System.out.println("Enter the word number");
wordno=Integer.parseInt(br.readLine());
int count=0;
for(int i=0;i<sentence.length();i++)
{
char ch=sentence.charAt(i);
if(ch==' ')
{
String str=sentence.substring(n,i);
count=count+1;
if(str.equals(word)&&count==wordno)
{
sentence.delete(n,i);
}
n=i+1;
}
}
System.out.println("The new sentence is : "+sentence);
}
}
這是工作程序
package com.nikhil.string;
import java.io.IOException;
import java.util.Scanner;
public class demo1 {
public static void main(String[] args) throws IOException {
String[] s;
String sentence, word;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence");
sentence = sc.nextLine();
System.out.println("Enter the word to be deleted");
word = sc.nextLine();
String finalSentence = "";
s = sentence.split(" ");
for (int i = 0; i < s.length; i++) {
if (word.equals(s[i])) {
continue;
} else {
finalSentence += s[i] + " ";
}
}
System.out.println("final sentence is :: " + finalSentence);
sc.close();
}
}
據我所知,您想從句子中刪除給定的單詞。 我的建議如下
- 閱讀句子(例如
String str="hi, How are you"
)- 選擇您要從句子中刪除的單詞。 (例如
String strToRemove="are"
)
然后,您可以嘗試以下操作。
String str = "hi, How are you?. are you there?";
String strToRemove = "are";
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(str);
boolean status=true;
while (status){
int index=stringBuilder.indexOf(strToRemove);
if(index!=-1) {
stringBuilder.delete(index, index + strToRemove.length()+1);
// +1 will remove a space
}else {
status=false;
}
}
System.out.println(stringBuilder.toString());
public static void main(String ar[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the sentence");
StringBuffer sentence = new StringBuffer(br.readLine() + " ");
System.out.println("Enter the word to be deleted");
String word = br.readLine();
String result = sentence.toString().replace(word, "");
System.out.println("The new sentence is : " + result);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.