Program to remove a word from a sentence - java

How can I modify the program without using word number option?
Please give me a simplified program.
What must I do to make this program work without word number?
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);
}
}

Here is the working program
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();
}
}

As far as I can see you want to remove given word from a sentence. My suggestion as follows
Read sentence (say String str="hi, How are you")
Take the word you want to remove from the sentence.
(say String strToRemove="are")
Then you can try something as follows.
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);
}

Related

Counting white-spaces in a String in java

I have written a program which takes a String as user input and displays the count of letters, digits and white-spaces. I wrote the code using the Tokenizer-class, and it counts the letters and digits, but it leaves out the white-spaces. Any ideas?
import java.util.Scanner;
public class line {
public static void main(String[] args) {
System.out.println("Enter anything you want.");
String text;
int let = 0;
int dig = 0;
int space= 0;
Scanner sc = new Scanner(System.in);
text = sc.next();
char[]arr=text.toCharArray();
for(int i=0;i<text.length();i++) {
if (Character.isDigit(arr[i])) {
dig++;
} else if (Character.isLetter(arr[i])) {
let++;
} else if (Character.isWhitespace(arr[i])) {
space++;
}
}
System.out.println("Number of Letters : "+let);
System.out.println("Number of Digits : "+dig);
System.out.println("Number of Whitespaces : "+space);
}
}
Scanner by default breaks the input into tokens, using whitespace as the delimiter!
Simply put, it gobbles up all the whitespace!
You can change the delimiter to something else using sc.useDelimiter(/*ToDo - suitable character here - a semicolon perhaps*/).
You have got problem in
sc.next();
except it, use
sc.nextLine();
it should work.
Instead of text = sc.next(); use text = sc.nextLine();
Try using
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Line {
public static void main(String[] args) throws Exception {
String s;
System.out.println("Enter anything you want.");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
s = br.readLine();
int length = s.length();
int letters = 0;
int numbers = 0;
int spaces = 0;
for (int i = 0; i < length; i++) {
char ch;
ch = s.charAt(i);
if (Character.isLetter(ch)) {
letters++;
} else {
if (Character.isDigit(ch)) {
numbers++;
} else {
if (Character.isWhitespace(ch)) {
spaces++;
} else
continue;
}
}
}
System.out.println("Number of letters::" + letters);
System.out.println("Number of digits::" + numbers);
System.out.println("Number of white spaces:::" + spaces);
}
}

using java.util.Stack print line of texts in reverse

Lines should be read from the user until the sentinel "DONE" is entered, at which point they are displayed in reverse. Do not print the word "DONE"
here is my code so far i am not sure how to get it all to work together i know i have been overthinking this but any help will be appreciated
import java.util.Scanner;
import java.util.Stack;
public class Turner_A05Q3{
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
ArrayList<String> list = new ArrayList<String>();
System.out.println("Enter text, or done to stop");
Scanner scanner = new Scanner(System.in);
List<String> al = new ArrayList<String>();
String word;
while (scanner.hasNextLine()) {
word = scanner.nextLine();
if (word != null) {
word = word.trim();
if (word.equalsIgnoreCase("done")) {
break;
}
al.add(word);
} else {
break;
}
}
for (int i=0;i<word.length();i++){
stack.push(word.substring(i,i+1));
}
String wordrev = "";
while(!stack.isEmpty()){
wordrev += stack.pop();
}
System.out.println("Reverse of the text \"" + wordrev);
}
}
Try to write your for loop like this:
for (int i = word.length(); i > 0; i--) {
stack.push(word.substring(i-1, i));
}
Input:
DONE
Output:
DONE
You are always working with the last word (done), because you don't use al you only use the last content of the variable word.
You have to iterate over al
Try:
import java.util.Scanner;
import java.util.Stack;
import java.util.ArrayList;
import java.util.List;
public class Turner_A05Q3{
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
System.out.println("Enter text, or done to stop");
Scanner scanner = new Scanner(System.in);
List<String> al = new ArrayList<String>();
String word=null;
while (scanner.hasNextLine()) {
word = scanner.nextLine();
if (word != null) {
word = word.trim();
if (word.equalsIgnoreCase("done")) {
break;
}
al.add(word);
}else {
break;
}
}
for(int j=0;j<al.size();j++){
word = al.get(j);
for (int i=0;i<word.length();i++){
stack.push(word.substring(i,i+1));
}
String wordrev = "";
while(!stack.isEmpty()){
wordrev += stack.pop();
}
System.out.println("Reverse of the text \"" + wordrev);
}
}
}
If you want to show the words in reversed order, not the characters, try:
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
System.out.println("Enter text, or done to stop");
Scanner scanner = new Scanner(System.in);
String word=null;
while (scanner.hasNextLine()) {
word = scanner.nextLine();
if (word != null) {
word = word.trim();
if (word.equalsIgnoreCase("done")) {
break;
}
stack.push(word);
}else {
break;
}
}
while(!stack.isEmpty()){
System.out.println("Reverse of the text \"" + stack.pop());
}
}
Remember that a Stack is LIFO (Last In First Out)

Accept a sentence and print the words that have same consecutive characters

Here is my homework:
accept a sentence and print the words that have consecutive characters equal
INPUT: an apple a day keeps
OUTPUT: apple keeps
Here is what I am working on:
import java.util.*;
public class Program1
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence");
String s=sc.nextLine();
String str=s.toLowerCase();
int l,i=0; char c,d;int a,b,m=0;int n=0; String r=""; String res="";
l=s.length();
str=" "+str+" ";
for(i=0;i<(l-1);i++)
{
c=str.charAt(i);
d=str.charAt(i+1);
a=c;
b=d;
m=str.indexOf(' ');
n=str.indexOf(' ',(i+1));
if(d==' ')
{
m=str.indexOf(' ',(i-1));
n=str.indexOf(' ',(i+1));
}
if(a==b)
{
r=str.substring(m,n);
res=res +" "+ r;
}
}
System.out.println(res);
}
}
It gets compiled, but it does not give correct output.
If I enter the above example, it returns:
an apple an apple a day keeps
What do I need to do?
You can do something like this to achieve the result,
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
String s = sc.nextLine();
String str = s.toLowerCase();
String[] words = str.split(" "); // Split the sentence into an array of words.
for(String ss : words){
char previousChar = '\u0000';
for (char c : ss.toCharArray()) {
if (previousChar == c) { // Same character has occurred
System.out.println(ss);
break;
}
previousChar = c;
}
}
The problem is in the line:
m=str.indexOf(' ');
you start aat the beginning of the sentence every time, so you print the sentence from beginning to the word you want.
This is my proposal. :-D
Input: mi aasas es mass pp
Output: aasas mass pp
import java.util.*;
public class code10
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence");
String s=sc.nextLine();
String str=s.toLowerCase();
String cadena = str;
String delimitadores= "[ .,;?!¡¿\'\"\\[\\]]+";
String[] palabrasSeparadas = cadena.split(delimitadores);
for(int x=0; x<palabrasSeparadas.length; x++)
{
char[] tmpstr = palabrasSeparadas[x].toCharArray();
for(int y=0; y<tmpstr.length; y++)
{
if((y+1) < tmpstr.length)
{
if(tmpstr[y] == tmpstr[y+1])
{
System.out.print(palabrasSeparadas[x] + " ");
}
}
}
}
System.out.println("");
}
}

ask the user for input (a sentence) and print out the longest word of that sentence

How do I have this program ask the user for input (a sentence) and print out the longest word of that sentence.
package projectOne;
import java.util.Scanner;
public class LongestWord {
//Scanner keyboard = new Scanner(System.in);
//System.out.println("In 1 sentence tell me what is on your mind today.");
//String actualstring = keyboard.nextLine();
static String actualstring = keyboard.nextLine();
static String[] splitstring = actualstring.split(" ");
public static void main(String [] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("In 1 sentence tell me what is on your mind today.");
//String actualstring = keyboard.nextLine();
//String[] splitstring = actualstring.split(" ");
LongWord();
}
public static void LongWord() {
String longword = "";
for (int i=0; i<=splitstring.length-1; i++){
if (longword.length()<splitstring[i].length())
longword = splitstring[i];
}
System.out.println(longword);
int replyLength = longword.length();
System.out.println(replyLength);
if (replyLength == 3)
System.out.println("Hmmm tell me more about "+longword+" please");
else if (replyLength == 4)
System.out.println("Why do you feel "+longword+" is important?");
else if (replyLength == 5)
System.out.println("How does "+longword+" affect you?");
else if (replyLength > 5)
System.out.println("We seem to be making great progress with "+longword);
else
System.out.println("Is there something else you would like to discuss?");
}
}
I don't think you quite understand how methods work. In your main you should prompt the user for the line they'd like to enter and then you should read the entire line intro a String using the Scanner.nextLine() method and then you should pass said String into your longWord method for processing.
public static void main(String [] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("In 1 sentence tell me what is on your mind today.");
String sentence = keyboard.nextLine();
longWord(sentence);
}
public static void longWord(String sentence) {
//Process and print the longest word using the passed in String param
//Splitting, looping, comparisons, output
}
Try:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String maxword = null;
str = str + ' ';
int l = str.length();
String word = "";
int maxlength = 0;
for (int i = 0; i < l; i++) {
word = word + str.charAt(i);
if (str.charAt(i + 1) == ' ') {
if (word.length() > maxlength) {
maxword = new String(word);
maxlength = word.length();
}
word = "";
i++;
}
}
System.out.println("Longest Word: " + maxword);
}

Removing inserted numbers from a String in java

Ok, so i have created a program that defines if the inserted word is a palindrome or not.
But i need help on removing numbers that where to be inserted in the string.
import java.util.*;
import java.util.Scanner;
class Palindrome
{
public static void main(String args[])
{
String reverse = "";
Scanner scan = new Scanner(System.in);
System.out.print("Type a sentence and press enter: ");
String input = scan.nextLine();
// use regex to remove the punctuation and spaces
String Input = input.replaceAll("\\W", " ");
System.out.println(Input);
int length = input.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse.replaceAll("\\W", "") + input.charAt(i);
System.out.println(reverse);
if (input.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
}
If you want to remove digits, try input.replaceAll("[0-9]","")
Try this........
public class T1 {
public static void main(String[] args){
String s = "1234ajhdhols233adfjal";
String[] arr = s.split("\\d");
String sx = new String();
for(String x : arr){
sx = sx+x;
}
System.out.println(sx);
}
}
Example:
public static void main(String[] args) {
String s = "1234ajhdhols233adfjal";
String str = s.replaceAll("\\d", "");
System.out.println(str);
}

Categories