I'm actually new in java and don't know the methods very well and I'm wonder how can I find a messed up word in a string like:
the string is : deadline is Deadline, so try not to extend DeaDLINE!!!
and the word I'm looking for is "liNedeAd"
yeah it's messed up and I wanna the program Ignore case too!
String str, word;
int count= 0;
str=in.nextLine();word=in.nextLine();
String a[] = str.split(" ");
for(int i = 0;i<a.length;i++) {
// what should I do here?
if (word.equals(a[i]))
count++;
}
System.out.println(count);
Really appreciate tell me the methods that I can use.
String#equalsIgnoreCase
Use this to compares a String to another ignoring case considerations.
There are many ways to solve your problem. I have listed a few of them and I suggest you to try some more ways once you have understood these ones.
import java.util.Arrays;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the sentence: ");
String str = in.nextLine();
System.out.print("Enter the word: ");
String word = in.nextLine();
long count = 0;
// Using Stream API
count = Arrays.stream(str.split("\\s+|\\p{Punct}")).filter(w -> w.equalsIgnoreCase(word)).count();
System.out.println(count);
// Pre-Java8 way
count = 0;
for (String w : str.split("\\s+|\\p{Punct}")) {
if (w.equalsIgnoreCase(word)) {
count++;
}
}
System.out.println(count);
// Using regex
count = 0;
Matcher matcher = Pattern.compile("(?i)\\b" + word + "\\b").matcher(str);
while (matcher.find()) {
count++;
}
System.out.println(count);
}
}
A sample run:
Enter the sentence: deadline is Deadline, so try not to extend DeaDLINE!!!
Enter the word: deadline
3
3
3
The regex, \s+|\p{Punct} means one or more whitespace characters or a punctuation character
(?i) in the beginning of a regex pattern makes it case-insensitive.
\b specifies a word boundary.
If you are looking to match anagrams, you can define a function to find if the two words are anagram and the rest of the processing will be same as above.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the sentence: ");
String str = in.nextLine();
System.out.print("Enter the word: ");
String word = in.nextLine();
long count = 0;
// Using Stream API
count = Arrays.stream(str.split("\\s+|\\p{Punct}")).filter(w -> anagrams(w, word)).count();
System.out.println(count);
// Pre-Java8 way
count = 0;
for (String w : str.split("\\s+|\\p{Punct}")) {
if (anagrams(w, word)) {
count++;
}
}
System.out.println(count);
}
static boolean anagrams(String str1, String str2) {
if (str1.length() == str1.length()) {
// Get the char[] from strings after converting them to the same case
char[] arr1 = str1.toLowerCase().toCharArray();
char[] arr2 = str2.toLowerCase().toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
return (Arrays.equals(arr1, arr2));
}
return false;
}
}
Output:
Enter the sentence: deadline is Deadline, so try not to extend DeaDLINE!!!
Enter the word: liNedeAd
3
3
Important links:
Lesson: Regular Expressions
Reference - What does this regex mean?
Processing Data with Java SE 8 Streams, Part 1
If you want to ignore cases, this would probably be the best option:
if(word.equalsIgnoreCase(a[i])
count++;
Another, less efficient way of doing it would be to use the toLowerCase() method on both strings.
Related
I wrote a small program that checks if strings are sorted in alphabetical order from user input on one line separated by whitespace. It works and that's great, but what I don't understand is why I can use scanner to create the array when the size has not been set. Any insight would be appreciated.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] stringArray = scanner.nextLine().split(" ");
boolean alphabetical = true;
for (int i = 1; i < stringArray.length; i++) {
if (stringArray[i].compareTo(stringArray[i - 1]) < 0) {
alphabetical = false;
break;
}
}
System.out.print(alphabetical);
}
}
The answer is to be found in this method: .split(" ");.
From the documentation:
split
public String[] split(String regex)
Splits this string around matches of the given regular expression.
[...]
Returns:
the array of strings computed by splitting this string around matches of the given regular expression
Write a method called countWords that accepts an ArrayList of String as argument and
prints out the number of words (i.e. Strings) that start with ―A‖ or ―a‖ and prints all words longer than 5 characters on one line.
My solution is like
int count=0;
String[] st=null;
Scanner input=new Scanner(System.in);
ArrayList<String> array = new ArrayList<String>();
System.out.println("please input something");
while(input.hasNext()) {
String st1=input.next();
array.add(st1);
}
for(int i=0; i<array.size();i++) {
if(array.get(i).startsWith("a")||array.get(i).startsWith("A")) {
count++;
}
}
for(int j=0; j<array.size(); j++) {
if(array.get(j).length()>5)
st[j]=array.get(j);
}
System.out.println(count);
System.out.println(st);
}
but there will be no end for typing in Strings
As the last line of your question said
but there will be no end for typing in Strings
Well That is because you did not provided any way to end the while loop.
while(input.hasNext())
Will run forever and ever waiting for next user input. You have to break the while loop once the inputting is done.
AFTERWARDS
As the question said "prints out the number of words that start with A or a and prints all words longer than 5 characters on one line."
For this you can loop through the ArrayList and check for
if(array.get(i).startsWith("A") || array.get(i).startsWith("a")) count++;
if(array.get(i).length()>5) System.out.print(array.get(i)+" ");
and print the number of A or a Occurrence after the loop
System.out.println("\n Number of word with A or a:"+count);
Here is a working implementation of your code
public static void main(String[] args) {
int count=0;
String[] st=null;
Scanner input=new Scanner(System.in);
ArrayList<String> array = new ArrayList<String>();
System.out.println("please input something");
//System.out.println(input.hasNext());
while(input.hasNext()) {
String st1=input.next();
//System.out.println((int) st1.charAt(0));
if(st1.equals("exit")) break;
array.add(st1);
}
for(int i=0; i<array.size();i++) {
if(array.get(i).startsWith("A") || array.get(i).startsWith("a")){
count++;
}
if(array.get(i).length()>5) {
System.out.print(array.get(i)+" ");
}
}
System.out.println("\nNumber of word with A or a:"+count);
}
to end the loop you have to type exit.
Here is a solution to your problem..
import java.util.Arrays;
import java.util.List;
public class Test {
public static void main(String... args){
// Sample String sentence
String sentence = "This is the sentence with 5 words starting with
all like allwords alltogether also Allnotout allother and allofus.";
// Splitting above sentence to get each word separately and storing them into List
List<String> strings = Arrays.asList(sentence.split("\\s+"));
// calling a method named countWord() as per your assignment question.
Test.countWords(strings);
}
// implementing that method
static void countWords(List<String> input){
long count = input.stream().filter(word -> word.startsWith("all") || word.startsWith("All")).count();
System.out.print("Total words starting with all/All are : "+ count +"\t");
input.stream().filter(word -> word.length() > 5).forEach( word -> System.out.print(word + "\t"));
}
}
I want to count the number of times "the" shows up in an array of tokens I made from user input and store it in a variable named "theCount". I'm iterating through the array with a for loop and checking for "the" with an if statement.
I am not allowed to use regular expressions.
This is what I have so far:
import java.util.*;
public class theCount
{
public static void main (String[] args)
{
Scanner userInput = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = userInput.nextLine();
String[] input = sentence.split(" the");
int theCount = 0;
for (String token : input) {
if (token == "the")
theCount++;
System.out.print("\n" + theCount); //I want it printed after
//iteration.
}
}
}
There are couple of problems:
split(" the") uses " the" as delimiter and gives rest of the words. Best is to split using whitespace.
Use token.equals("the") instead of ==.
if you want to count number of occurrence use this sample code:
import java.util.*;
public class theCount {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = userInput.nextLine();
int theCount = sentence.length() - sentence.replace("the", "").length();
System.out.print("Number of occurrence: " + theCount);
}
}
You can add the input to a arraylist and then can play around with it.
One way is to get the count from frequency method.
List<String> arrayList = new ArrayList<String>();
arrayList.add("String"); //add all the words.
Collections.frequency(arrayList, "the");
Second way is to get the count from map.
Map<String, Integer> map = new HashMap<String, Integer>();
for(String s : arrayList){
Integer count = map.get(s);
map.put(s, count==null?1:count+1);
}
//the below will give you the count of any word.
map.get("the");
As of Java 8 you could you stream api to solve this. That will be more concise. Take the following code as example
public static void main(String[] args) {
String str = "The is the for THE and the the the the The The";
long count = Stream.of(str.split(" "))
.filter(i -> i.equalsIgnoreCase("the"))
.count();
System.out.println(count);
}
=== Update ===
public static void main(String[] args) {
String str = " there these theology";
long count = Stream.of(str.split(" "))
.map(String ::toLowerCase)
.filter(i -> i.contains("the"))
.count();
System.out.println(count);
}
=== Update ===
This solution will work even there are multiple same sub strings in a string.
public static void main(String[] args) {
String str = " thesethefajfskfjthetheasdfjasdkfjthe";
String findStr = "the";
int count = 0;
for (String s : str.split(" ")) {
count += s.toLowerCase()
.split(findStr, -1).length - 1 ;
}
System.out.println(count);
}
This SO post will help you to understand, how to find all sub string in a single string.
So first of all, hello everyone this is my first time stackoverflow as a question asker and I know you folks don't like people asking homework questions on here but I've been struggling with this for about a week now and have given it several reasonable attempts so I actually need help here and am not just trying to mooch answers off you amazing coders :)
So my task at hand is I'm trying (the language is java btw) to find the number of times a letter (which the user inputs) occurs in a word (which the user also picks, and then to output the number of time that word occurs, for example: the word hello has two 'l's in it.. it should be pretty easy but for some reason I can't get it :/
I believe using my current code the variable "let" gets turned into an ascii character and idk what to do with that, or rather how I should compare it with all the other characters in the word.
Please help :)
import java.util.Scanner;
public class LetterCounter {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String word = "";
String letter;
int limit = 0;
String input = null;
String let;
int count = 0;
int j = 0;
while(limit == 0){
System.out.println("Type a word.");
word = scan.nextLine();
System.out.println("Type a single letter.");
letter = scan.nextLine();
let = letter.substring(0,1);
char car;
while(j<word.length()){
car = word.charAt(j);
for(int x=1; x==j; x++){
if(let.charAt(0)==car){
count ++;
}
}
j+=1;
}
System.out.println(count + " " + "occurances.");
}
}
}
Here is a sample code that should work
import java.util.Scanner;
public class LetterCounter {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Type a word.");
String word = scan.nextLine();
System.out.println("Type a single letter.");
String letter = scan.nextLine();
char let = letter.charAt(0);
int count = 0;
for (char char1: word.toCharArray()) {
if (char1 == let) {
count++;
}
}
System.out.println(count + " " + "occurrences.");
}
}
Here is the test output
Type a word.
letter
Type a single letter.
t
2 occurrences.
So I'm new to programming. I'm using java. Right now I have an assignment I can't solve on a website that teaches java.
This is the assignment
Write a program that returns number of occurrences of a string in another string.
E.g
Input:
First String: the
Second String: The children are playing with their toys because they love it.
Output:
3
Note: You should only use nested loops. Don’t use methods like indexOf or substring.
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
String a = input.nextLine();
String b = input.nextLine();
String z[] = b.split(" ");
int number=0;
for (int i =0; i<z.length; i++){
if (z[i].contains(a))number++;
}
System.out.println(number);
I won't give you too much code, but here are the main talking points:
You need a way to read the input in. This can be accomplished with a Scanner - it's either from STDIN or a file.
You need a way to break up each word in the sentence. String#split will help you with that.
You need a way to ignore the casing of each sentence - toLowerCase() works well here.
You need to loop over each word in one sentence, as well as each occurrence in the other sentence. Consider that String.split produces a String[], and you can iterate over that with any standard for loop.
You need a way to see is a string is contained in another string. String#contains will help - although you want to be very careful on which side you're asking contains a string. For example:
// This will print true
System.out.println("The world".toLowerCase().contains("the"));
// This will print false
System.out.println("the".contains("The world".toLowerCase()));
Try this :
import java.util.Scanner;
public class Occurence {
/**
* #param args
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str1 = input.nextLine();
String str2 = input.nextLine();
int count = 0;
String word[] = str1.split(" ");
for (int i = 0; i < word.length; i++) {
if (word[i].toLowerCase().contains(str2.toLowerCase())) {
count++;
}
}
System.out.println("Occurence = " + count);
}
}