To Reduce a String - java

I was solving a problem to reduce the form to it's non-reducible form. This was the question.
Shil has a string S , consisting of N lowercase English letters. In one operation, he can delete any pair of adjacent letters with same value. For example, string "aabcc" would become either "aab" or "bcc" after operation.
Shil wants to reduce S as much as possible. To do this, he will repeat the above operation as many times as it can be performed. Help Shil out by finding and printing 's non-reducible form!
If the final string is empty, print Empty String; otherwise, print the final non-reducible string.
Sample Input 0
aaabccddd
Sample Output 0
abd
Sample Input 1
baab
Sample Output 1
Empty String
Sample Input 2
aa
Sample Output 2
Empty String
Explanation
Sample Case 0:
Shil can perform the following sequence of operations to get the final string:
Thus, we print .
Sample Case 1:
Shil can perform the following sequence of operations to get the final string:
aaabccddd -> abccddd
abccddd -> abddd
abddd -> abd
Thus we print abd
Sample case 1:
baab -> bb
bb -> Empty String.
And what I have done till now is try to solve it through StringBuilder in Java.But some of testcases pass while other's don't and I can't find out what's the error?
Here is the code that I have tried so far.
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
StringBuilder sb = new StringBuilder(scan.nextLine());
for(int i = 0; i < sb.length()-1; i++)
{
if(sb.charAt(i) == sb.charAt(i+1))
sb.delete(i,i+2);
i = 0;
}
if(sb.length() == 0)
System.out.println("Empty String");
else
System.out.println(sb.toString());
}
}
Inputs like aaabccddd
and aa pass.But when the input is baab it fails.

You have to use a while loop. Problem with your code is that it just iterate through the code just one time. In first iteration though your input "baab" becomes "bb", then it checks 2nd b and try to find a "b" in i+1 (which does not exist). change your for loop to a while loop as below.
import java.util.Scanner;
public class Solution{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
StringBuilder sb = new StringBuilder(scan.nextLine());
int c=0;
while(c< sb.length()-1){
if(sb.charAt(c) == sb.charAt(c+1)){
sb.delete(c,c+2);
c=0;
}
else{
c+=1;
}
}
if(sb.length() == 0)
System.out.println("Empty String");
else
System.out.println(sb.toString());
}
}

The problem is you just run loop through the string for one time.
For example:
String "baab", you just delete "aa" and finish the loop.
Solution: use recursion with a flag isNonReducible, loop until it give empty string or flag isNonReducible = true;
public class Solution {
public static StringBuilder checkReducible(StringBuilder sb) {
boolean isNonReducible = true;
for (int i = 0; i < sb.length() - 1; i++) {
if (sb.charAt(i) == sb.charAt(i + 1)) {
isNonReducible = false;
sb.delete(i, i + 2);
}
}
if (sb.length() == 0) {
return new StringBuilder("Empty String");
}
else {
if(!isNonReducible) {
sb = checkReducible(sb);
}
return sb;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
StringBuilder sb = new StringBuilder(scan.nextLine());
System.out.println(checkReducible(sb));
scan.close();
}
}

you can do with the help of lable try this,
public static void main(String[] args) {
boolean canReduce = true;
Scanner scan = new Scanner(System.in);
StringBuilder sb = new StringBuilder(scan.nextLine());
startPoint: while (sb.length() > 0 && canReduce) {
for (int i = 0; i < sb.length() - 1; i++) {
if (sb.charAt(i) == sb.charAt(i + 1)) {
sb.delete(i, i + 2);
canReduce=true;
continue startPoint;
}else{
canReduce=false;
}
}
}
if (sb.length() == 0) {
System.out.println("Empty String");
} else {
System.out.println(sb.toString());
}
}

Try this:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
StringBuilder sb =new StringBuilder(in.nextLine());
for (int i=0; i<sb.length()-1; i++){
if(sb.charAt(i)==sb.charAt(i+1)){
sb.delete(i, i+2);
i=-1;
}
}
if(sb.length()==0){
System.out.println("Empty String");
}else{
System.out.println(sb);
}
}

Related

How to use a loop to capitalize first occurring lowercase letter of string Java

Prompt: Use a loop to find the first occurring lowercase letter in the input string.
Then capitalize ONLY the lowercase letter you found, and then re-combine it with the rest of the string.
I'm so confused because one I don't know the exact number of indexes because it varies and two how can I capitalize only the first occurring lowercase. For example inputs are like BYus where I'm only supposed to capitalize the u. I have
public class PasswordImprover {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String userInput;
userInput = sc.next();
int userLowerCase = userInput.indexOf(".*[a-z].*");
for (int i = 0; i < userInput.length(); i++) {
if (Character.isLowerCase(userInput.charAt(i))) {
System.out.print(userInput.toUpperCase().charAt(i));
} else if (!userInput.contains(".*[a-z].*")) {
System.out.print(userInput.charAt(i));
}
}
}
}
but this just outputs everything in uppercase. Please help.
Get rid of that regex and just use a simple loop and a flag to indicate that you have process the first LC char
Scanner sc = new Scanner(System.in);
String userInput= sc.next();
boolean done = false;
for (int i = 0; i < userInput.length(); i++) {
if (!done && Character.isLowerCase(userInput.charAt(i))) {
System.out.print(userInput.toUpperCase().charAt(i));
done = true;
}
else {
System.out.print(userInput.charAt(i));
}
}
I'm so confused because one I don't know the exact number of indexes because it varies
Yes, that would the reason for the loop
how can I capitalize only the first occurring lowercase
Well, there's a few ways you might do it. String#substring might be starting point, for example...
public class Test {
public static void main(String[] args) {
String test = "BYus";
StringBuilder sb = new StringBuilder(test);
for (int index = 0; index < sb.length(); index++) {
if (Character.isLowerCase(sb.charAt(index))) {
test = test.substring(0, index) + Character.toUpperCase(test.charAt(index)) + test.substring(index + 1);
break;
}
}
System.out.println(test);
}
}
or, if you want to be a little more efficient, you could use a StringBuilder, for example...
public class Test {
public static void main(String[] args) {
String test = "BYus";
StringBuilder sb = new StringBuilder(test);
for (int index = 0; index < sb.length(); index++) {
if (Character.isLowerCase(sb.charAt(index))) {
sb.replace(index, index + 1, Character.toString(test.charAt(index)).toUpperCase());
break;
}
}
test = sb.toString();
System.out.println(test);
}
}
You could also convert the String to a character array and simply replace the first lower cased character in it and build a new String at the end, for example...
public class Test {
public static void main(String[] args) {
String test = "BYus";
char[] characters = test.toCharArray();
for (int index = 0; index < characters.length; index++) {
if (Character.isLowerCase(characters[index])) {
characters[index] = Character.toUpperCase(test.charAt(index));
break;
}
}
test = new String(characters);
System.out.println(test);
}
}
So, you know, options
You can iterate over the input as an array of chars:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string ");
char[] userInput = sc.next().toCharArray();
for (int i = 0; i < userInput.length; i++) {
if (Character.isLowerCase(userInput[i])) {
userInput[i] = Character.toUpperCase(userInput[i]);
break;
}
}
System.out.println(String.valueOf(userInput));
}
An example for regex.
String str = "BYus";
str = str.replaceFirst("([^a-z]*.).*", "$1").toUpperCase() + str.replaceFirst("[^a-z]*.(.*)", "$1");
System.out.println(str); //BYUs

Find common alphabets in two strings using for loop

I am trying to find the common characters in two strings just by using the for loop. The below code is working fine, if I provide two completely different strings ex.one and two but if I provide two strings with same input ex.teen and teen it doesn't work as expected.
import java.util.Scanner;
public class CommonAlphabets {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in)){
System.out.println("Enter String one ");
String stringOne = input.nextLine();
System.out.println("Enter String two ");
String StringTwo = input.nextLine();
StringBuffer sb = new StringBuffer();
for(int i=0;i<stringOne.length();i++){
for(int j=0;j<StringTwo.length();j++){
if(stringOne.charAt(i)== StringTwo.charAt(j)){
sb.append(stringOne.charAt(i));
}
}
}
System.out.println("Common characters are " +sb.toString());
}
}
}
Should I create another nested for loop to find duplicates in the StringBuffer or is there a better way to handle this scenario.
You do not need an inner for loop but use contains instead
String stringOne = "one";
String stringTwo = "one";
StringBuilder sb = new StringBuilder();
for(int i=0;i<stringOne.length() && i < stringTwo.length ();i++){
if(stringOne.contains(String.valueOf(stringTwo.charAt(i))) &&
!sb.toString().contains(String.valueOf(stringTwo.charAt(i)))){
// check already added
sb.append(stringTwo.charAt(i));
}
}
System.out.println (sb.toString());
edit
check to make sure char to be added does not already exist in StringBuilder -
Could use a Set instead
If using a Set
Set<Character> set = new HashSet<> ();
your logic could be simplified to
if(stringOne.contains(String.valueOf(stringTwo.charAt(i)))){
set.add(stringTwo.charAt(i));
}
You can use Set for it.
Set<Character> set = new HashSet<>();
for(int i = 0; i<stringOne.length(); i++) {
for(int j = 0; j < StringTwo.length(); j++) {
if(stringOne.charAt(i) == StringTwo.charAt(j)){
set.add(stringOne.charAt(i));
}
}
}
StringBuilder sb = new StringBuilder();
for (Character c : set) {
sb.append(c);
}
System.out.println("Common characters are " + sb);
well your approach is fine as the result is showing what you are expecting there fore that code is fine, but you need to stop the duplication , therefore you have to write the code for 'sb' variable so that it will remove duplicates or write code in loop so that it wont provide duplicate.
as your code is becoming complicated to read so i would prefer that you make a method to write code to remove duplicate it will go like
static void removeDuplicate(StringBuilder s){
for(int i=0,i<s.length-1,i++){
for(int j=i+1,j<s.length,j++){
if(s.charAt(i)==s.charAt(j)){
s.deleteCharAt(j);
}
}
}
call this method before printing
Another approach you could try is - combine the two input strings, iterate over the concatenated string and return the characters which exist in both the strings.
Using a Set will ensure you do not add characters which get repeated due to the concatenation of the strings.
Here's what I wrote -
import java.util.HashSet;
public class HelloWorld {
private static Character[] findCommonLetters(String combined, String w1, String w2) {
HashSet<Character> hash = new HashSet<>();
for(char c: combined.toCharArray()) {
if(w1.indexOf(c) != -1 && w2.indexOf(c) != -1) {
hash.add(c);
}
}
return hash.toArray(new Character[hash.size()]);
}
public static void main(String []args){
// System.out.println("Hello World");
String first = "flour";
String second = "four";
String combined = first.concat(second);
Character[] result = findCommonLetters(combined, first, second);
for(char c: result) {
System.out.print(c);
}
System.out.println();
}
}
Demo here.
This is the best way to do this because it's time complexity is n so that why this is the best you could do.
import java.util.Scanner;
public class CommonAlphabets
{
public static void main(String[] args)
{
try (Scanner input = new Scanner(System.in))
{
System.out.println("Enter String one ");
String stringOne = input.nextLine();
System.out.println("Enter String two ");
String StringTwo = input.nextLine();
StringBuffer sb = new StringBuffer();
/**
* Assuming char as index of array where A-Z is from index 0 to 25 and a-z is index 26-51
*/
int[] alphabetArray1 = new int[52];
for(int i = 0, len = stringOne.length(); i < len; i++)
alphabetArray1[stringOne.charAt(i) > 94 ? stringOne.charAt(i) - 71 : stringOne.charAt(i) - 65] = 1;
int[] alphabetArray2 = new int[52];
for(int i = 0, len = StringTwo.length(); i < len; i++)
alphabetArray2[StringTwo.charAt(i) > 94 ? StringTwo.charAt(i) - 71 : StringTwo.charAt(i) - 65] = 1;
// System.out.println(Arrays.toString(alphabetArray1));
// System.out.println(Arrays.toString(alphabetArray2));
for (int i = 0; i < 52; i++)
if (alphabetArray1[i] == 1 && alphabetArray2[i] == 1)
sb.append((char) (i < 26 ? i + 65 : i + 71));
System.out.println("Common characters are " + sb.toString());
}
}
}

Determining a Palindrome using Stack and Queue in java

Here I am trying to determine if a word or phrase is a palindrome by using stacks and queues depending on the phrase I write in.
What it is doing is that it says that everything is a palindrome and writes "Palindrome" by how many letters it has.
I'm guessing that I need to add something between the last for loop and the while loop, but I'm not sure what.
public class CheckPalindrome {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String line = reader.readLine();
if (line.toLowerCase().equals("quit")) {
break;
}
Stack<Character> stack = new Stack<Character>();
Queue<Character> queue = new LinkedList<Character>();
for (int i = 0; i < line.length(); i++) {
stack.push(line.charAt(i));
}
for (int i = line.length() - 1; i >= 0; i--) {
queue.add(line.charAt(i));
}
while (!queue.isEmpty()) {
if (queue.remove().equals(stack.pop())) {
System.out.println("Palindrome");
} else {
System.out.println("Not a Palindrome");
}
}
}
}
}
I made some very minor modifications (first to fix one of your for loops, and second to prevent your "Palindrome/Not a Palindrome" message from printing once for every character in the input) to your code to get it to work:
import java.util.Stack;
import java.util.LinkedList;
import java.util.Queue;
import java.io.*;
class Palindrome {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String line = reader.readLine();
if (line.toLowerCase().equals("quit")) {
break;
}
Stack<Character> stack = new Stack<Character>();
Queue<Character> queue = new LinkedList<Character>();
for (int i = 0; i < line.length(); i++) {
stack.push(line.charAt(i));
}
for (int i = 0; i < line.length(); i++) {
queue.add(line.charAt(i));
}
boolean isPalindrome=true;
while (!queue.isEmpty()) {
if (queue.remove().equals(stack.pop())) {
continue;
} else {
isPalindrome=false;
break;
}
}
if (!isPalindrome) {
System.out.println("Not a Palindrome");
} else {
System.out.println("Palindrome");
}
}
}
}
You need to put the characters into each of the stack and the queue in the same order. The point of using both is that one reverses the order and the other doesn't. Reversing the order yourself on one of them, as you are doing now, negates that.
Incase it's of interest, here's a variation on your approach using a Deque<E> as opposed to a Stack and Queue separately. A Deque is just a double ended queue (i.e. operates as both).
public static boolean isPalindrome(String word) {
boolean isPalindrome = word.length() == 1;
if (!isPalindrome) {
Deque<Character> wordDeque = new LinkedList<>();
for (Character c : word.toCharArray()) {
wordDeque.add(Character.toLowerCase(c));
}
isPalindrome = true;
while (isPalindrome && wordDeque.size() > 1) {
isPalindrome = wordDeque.pollFirst().compareTo(wordDeque.pollLast()) == 0;
}
}
return isPalindrome;
}
Here is new Solution. Try this one. If any modification ,let me know.
package Stack;
public class pallindrome {
Stack<Integer> stack = new Stack<Integer>();
Queue<Integer> queue = new LinkedList<Integer>();
void pushh(int new_Data) {
stack.push(new_Data);
}
void enquee(int new_Data) {
queue.add(new_Data);
}
int popStack(){
return stack.pop();
}
int dequeueQueue() {
return queue.remove();
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
scan.close();
// Convert input String to an array of characters:
char[] s = input.toCharArray();
// Create a Solution object:
pallindrome p = new pallindrome();
// Enqueue/Push all Integer to their respective data structures:
for(int i=0;i<input.length();i++)
{
p.pushh(i);
p.enquee(i);
}
// Pop/Dequeue the chars at the head of both data structures and compare them:
boolean isPalindrome = true;
for ( i = 0; i < s.length/2; i++) {
if (p.popStack() != p.dequeueQueue()) {
isPalindrome = false;
break;
}
}
//Finally, print whether string s is palindrome or not.
System.out.println( "The Integer, " + input + ", is "
+ ( (!isPalindrome) ? "not a palindrome." : "a palindrome." ) );
}
}
Using both stack and queue together for checking palindrome in JAVA
public class Palindrome {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the String:: ");
String real = input.nextLine();
Queue q = new LinkedList();
Stack st = new Stack();
for(int i=0; i<=real.length()-1; i++) {
q.add(real.charAt(i));
}
for(int i=0; i<real.length(); i++) {
st.push(real.charAt(i));
}
if(q.remove().equals(st.pop())) {
System.out.println("Palindrom");
}else {
System.out.println("Not Palindrom");
}
}
}

Removing white spaces from string using loops

Hi guys I'm trying to remove white spaces using loops specifically. Heres what I've come up with so far
import java.util.Scanner;
public class Q2 {
public static void main(String[] args) {
String input = "";
char noSpace = ' ';
Scanner scan = new Scanner(System.in);
input = scan.nextLine();
System.out.println(input);
for (int i = 0; i < input.length(); i++) { //search from right to left
for (int j = input.length(); j != -1; j--) { //search from left to right
if (input.charAt(i) == noSpace) { //if there is a space move position of i and j
i++;
j--;
}
}
System.out.println(input);
I am still quite new to java, any suggestions would be great thanks!
Try this one:
public class RemoveWhiteSpace {
public static void main(String[] args) {
String str = "Hello World... Hai... How are you? .";
for(Character c : str.toCharArray()) {
if(!Character.isWhitespace(c)) // Check if not white space print the char
System.out.print(c);
}
}
}
Why you do not use regular expressions? replaceAll("\\s","") removes all whitespaces. Also you can remove other non visible symbols, such as \tab etc.
Look at docs.oracle.com for more info
And a combination of themes...
StringBuilder result = new StringBuilder(64);
String str = "sample test";
for (Character c : str.toCharArray()) {
if (!Character.isWhitespace(c)) {
result.append(c);
}
}
System.out.println(result.toString()); // toString is not required, but I've had to many people assume that StringBuilder is a String
System.out.println(str.replace(" ", ""));
System.out.println("Double spaced".replace(" ", ""));
Basically, nothing new, just runnable examples of what every body else has spoken about...
import java.util.Scanner;
public class Iterations{
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = kb.nextLine();
String temp = "";
for (int i = 0; i < s.length(); i++){ //This loops separates the string into each character
String c = s.substring(i, i+1);
if (c.equals(" ")){
System.out.print(c.trim()); //If the individual character is space then remove it with trim()
} else {
temp = temp + c; //Adds the string up into single sentence
}
}
System.out.println(temp); //Print it to have a nice line of string
}
}
I am also new to java and happen to do problems that remove spaces with only some methods and loops. Thats my solution, feel free to try it out.
public class sample {
public static void main(String[] args) {
String input = "sample test";
char noSpace = ' ';
System.out.println("String original:"+input);
for (int i = 0; i < input.length(); i++) { //search from right to left
if (input.charAt(i) != noSpace) { //if there is a space move position of i and j
System.out.print(input.charAt(i));
}
}
}
}
You've actually gone too far by keeping two loops you could do it in one only:
public static void main(String[] args) {
String input = "";
char space = ' ';
Scanner scan = new Scanner(System.in);
input = scan.nextLine();
System.out.println(input);
for (int i = 0; i < input.length(); i++) { // search from right to left char by char
if (input.charAt(i)!= space) { // if the char is not space print it.
System.out.print(input.charAt(i));
}
}
}

Java word count program

I am trying to make a program on word count which I have partially made and it is giving the correct result but the moment I enter space or more than one space in the string, the result of word count show wrong results because I am counting words on the basis of spaces used. I need help if there is a solution in a way that no matter how many spaces are I still get the correct result. I am mentioning the code below.
public class CountWords
{
public static void main (String[] args)
{
System.out.println("Simple Java Word Count Program");
String str1 = "Today is Holdiay Day";
int wordCount = 1;
for (int i = 0; i < str1.length(); i++)
{
if (str1.charAt(i) == ' ')
{
wordCount++;
}
}
System.out.println("Word count is = " + wordCount);
}
}
public static void main (String[] args) {
System.out.println("Simple Java Word Count Program");
String str1 = "Today is Holdiay Day";
String[] wordArray = str1.trim().split("\\s+");
int wordCount = wordArray.length;
System.out.println("Word count is = " + wordCount);
}
The ideas is to split the string into words on any whitespace character occurring any number of times.
The split function of the String class returns an array containing the words as its elements.
Printing the length of the array would yield the number of words in the string.
Two routes for this. One way would be to use regular expressions. You can find out more about regular expressions here. A good regular expression for this would be something like "\w+" Then count the number of matches.
If you don't want to go that route, you could have a boolean flag that remembers if the last character you've seen is a space. If it is, don't count it. So the center of the loop looks like this:
boolean prevCharWasSpace=true;
for (int i = 0; i < str1.length(); i++)
{
if (str1.charAt(i) == ' ') {
prevCharWasSpace=true;
}
else{
if(prevCharWasSpace) wordChar++;
prevCharWasSpace = false;
}
}
Update
Using the split technique is exactly equivalent to what's happening here, but it doesn't really explain why it works. If we go back to our CS theory, we want to construct a Finite State Automa (FSA) that counts words. That FSA may appear as:
If you look at the code, it implements this FSA exactly. The prevCharWasSpace keeps track of which state we're in, and the str1.charAt('i') is decideds which edge (or arrow) is being followed. If you use the split method, a regular expression equivalent of this FSA is constructed internally, and is used to split the string into an array.
Java does have StringTokenizer API and can be used for this purpose as below.
String test = "This is a test app";
int countOfTokens = new StringTokenizer(test).countTokens();
System.out.println(countOfTokens);
OR
in a single line as below
System.out.println(new StringTokenizer("This is a test app").countTokens());
StringTokenizer supports multiple spaces in the input string, counting only the words trimming unnecessary spaces.
System.out.println(new StringTokenizer("This is a test app").countTokens());
Above line also prints 5
You can use String.split (read more here) instead of charAt, you will get good results.
If you want to use charAt for some reason then try trimming the string before you count the words that way you won't have the extra space and an extra word
My implementation, not using StringTokenizer:
Map<String, Long> getWordCounts(List<String> sentences, int maxLength) {
Map<String, Long> commonWordsInEventDescriptions = sentences
.parallelStream()
.map(sentence -> sentence.replace(".", ""))
.map(string -> string.split(" "))
.flatMap(Arrays::stream)
.map(s -> s.toLowerCase())
.filter(word -> word.length() >= 2 && word.length() <= maxLength)
.collect(groupingBy(Function.identity(), counting()));
}
Then, you could call it like this, as an example:
getWordCounts(list, 9).entrySet().stream()
.filter(pair -> pair.getValue() <= 3 && pair.getValue() >= 1)
.findFirst()
.orElseThrow(() ->
new RuntimeException("No matching word found.")).getKey();
Perhaps flipping the method to return Map<Long, String> might be better.
Use split(regex) method. The result is an array of strings that was splited by regex.
String s = "Today is Holdiay Day";
System.out.println("Word count is = " + s.split(" ").length);
You need to read the file line by line and reduce the multiple occurences of the whitespaces appearing in your line to a single occurence and then count for the words. Following is a sample:
public static void main(String... args) throws IOException {
FileInputStream fstream = new FileInputStream("c:\\test.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int wordcount = 0;
while ((strLine = br.readLine()) != null) {
strLine = strLine.replaceAll("[\t\b]", "");
strLine = strLine.replaceAll(" {2,}", " ");
if (!strLine.isEmpty()){
wordcount = wordcount + strLine.split(" ").length;
}
}
System.out.println(wordcount);
in.close();
}
public class wordCOunt
{
public static void main(String ar[])
{
System.out.println("Simple Java Word Count Program");
String str1 = "Today is Holdiay Day";
int wordCount = 1;
for (int i = 0; i < str1.length(); i++)
{
if (str1.charAt(i) == ' '&& str1.charAt(i+1)!=' ')
{
wordCount++;
}
}
System.out.println("Word count is = " +(str1.length()- wordCount));
}
}
public class wordCount
{
public static void main(String ar[]) throws Exception
{
System.out.println("Simple Java Word Count Program");
int wordCount = 1,count=1;
BufferedReader br = new BufferedReader(new FileReader("C:/file.txt"));
String str2 = "", str1 = "";
while ((str1 = br.readLine()) != null) {
str2 += str1;
}
for (int i = 0; i < str2.length(); i++)
{
if (str2.charAt(i) == ' ' && str2.charAt(i+1)!=' ')
{
wordCount++;
}
}
System.out.println("Word count is = " +(wordCount));
}
}
you should make your code more generic by considering other word separators as well.. such as "," ";" etc.
public class WordCounter{
public int count(String input){
int count =0;
boolean incrementCounter = false;
for (int i=0; i<input.length(); i++){
if (isValidWordCharacter(input.charAt(i))){
incrementCounter = true;
}else if (incrementCounter){
count++;
incrementCounter = false;
}
}
if (incrementCounter) count ++;//if string ends with a valid word
return count;
}
private boolean isValidWordCharacter(char c){
//any logic that will help you identify a valid character in a word
// you could also have a method which identifies word separators instead of this
return (c >= 'A' && c<='Z') || (c >= 'a' && c<='z');
}
}
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multiset;
String str="Simple Java Word Count count Count Program";
Iterable<String> words = Splitter.on(" ").trimResults().split(str);
//google word counter
Multiset<String> wordsMultiset = HashMultiset.create();
for (String string : words) {
wordsMultiset.add(string.toLowerCase());
}
Set<String> result = wordsMultiset.elementSet();
for (String string : result) {
System.out.println(string+" X "+wordsMultiset.count(string));
}
public static int CountWords(String str){
if(str.length() == 0)
return 0;
int count =0;
for(int i=0;i< str.length();i++){
if(str(i) == ' ')
continue;
if(i > 0 && str.charAt(i-1) == ' '){
count++;
}
else if(i==0 && str.charAt(i) != ' '){
count++;
}
}
return count;
}
public class CountWords
{
public static void main (String[] args)
{
System.out.println("Simple Java Word Count Program");
String str1 = "Today is Holdiay Day";
int wordCount = 1;
for (int i = 0; i < str1.length(); i++)
{
if (str1.charAt(i) == ' ' && str1.charAt(i+1)!=' ')
{
wordCount++;
}
}
System.out.println("Word count is = " + wordCount));
}
}
This gives the correct result because if space comes twice or more then it can't increase wordcount. Enjoy.
try this
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class wordcount {
public static void main(String[] args) {
String s = "India is my country. I love India";
List<String> qw = new ArrayList<String>();
Map<String, Integer> mmm = new HashMap<String, Integer>();
for (String sp : s.split(" ")) {
qw.add(sp);
}
for (String num : qw) {
mmm.put(num, Collections.frequency(qw, num));
}
System.out.println(mmm);
}
}
To count total words Or to count total words without repeat word count
public static void main(String[] args) {
// TODO Auto-generated method stub
String test = "I am trying to make make make";
Pattern p = Pattern.compile("\\w+");
Matcher m = p.matcher(test);
HashSet<String> hs = new HashSet<>();
int i=0;
while (m.find()) {
i++;
hs.add(m.group());
}
System.out.println("Total words Count==" + i);
System.out.println("Count without Repetation ==" + hs.size());
}
}
Output :
Total words Count==7
Count without Repeatation ==5
Not sure if there is a drawback, but this worked for me...
Scanner input = new Scanner(System.in);
String userInput = input.nextLine();
String trimmed = userInput.trim();
int count = 1;
for (int i = 0; i < trimmed.length(); i++) {
if ((trimmed.charAt(i) == ' ') && (trimmed.charAt(i-1) != ' ')) {
count++;
}
}
You can use this code.It may help you:
public static void main (String[] args)
{
System.out.println("Simple Java Word Count Program");
String str1 = "Today is Holdiay Day";
int count=0;
String[] wCount=str1.split(" ");
for(int i=0;i<wCount.length;i++){
if(!wCount[i].isEmpty())
{
count++;
}
}
System.out.println(count);
}
String data = "This world is mine";
System.out.print(data.split("\\s+").length);
This could be as simple as using split and count variable.
public class SplitString {
public static void main(String[] args) {
int count=0;
String s1="Hi i love to code";
for(String s:s1.split(" "))
{
count++;
}
System.out.println(count);
}
}
public class TotalWordsInSentence {
public static void main(String[] args) {
String str = "This is sample sentence";
int NoOfWOrds = 1;
for (int i = 0; i<str.length();i++){
if ((str.charAt(i) == ' ') && (i!=0) && (str.charAt(i-1) != ' ')){
NoOfWOrds++;
}
}
System.out.println("Number of Words in Sentence: " + NoOfWOrds);
}
}
In this code, There wont be any problem regarding white-space in it.
just the simple for loop. Hope this helps...
To count specified words only like John, John99, John_John and John's only. Change regex according to yourself and count the specified words only.
public static int wordCount(String content) {
int count = 0;
String regex = "([a-zA-Z_’][0-9]*)+[\\s]*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(content);
while(matcher.find()) {
count++;
System.out.println(matcher.group().trim()); //If want to display the matched words
}
return count;
}
class HelloWorld {
public static void main(String[] args) {
String str = "User is in for an interview";
int counter=0;
String arrStr[] = str.split(" ");
for (int i = 0; i< arrStr.length; i++){
String charStr = arrStr[i];
for(int j=0; j<charStr.length(); j++) {
if(charStr.charAt(j) =='i') {
counter++;
}
}
}
System.out.println("i " + counter);
}
}
public class CountWords {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string :");
String str = sc.nextLine();
System.out.println("length is string is :"+str.length());
int worldCount = 1;
for(int i=0; i<str.length(); i++){
if(str.charAt(i) == ' '){
worldCount++;
}
}
System.out.println(worldCount);
}
}
The full program working is:
public class main {
public static void main(String[] args) {
logicCounter counter1 = new logicCounter();
counter1.counter("I am trying to make a program on word count which I have partially made and it is giving the correct result but the moment I enter space or more than one space in the string, the result of word count show wrong results because I am counting words on the basis of spaces used. I need help if there is a solution in a way that no matter how many spaces are I still get the correct result. I am mentioning the code below.");
}
}
public class logicCounter {
public void counter (String str) {
String str1 = str;
boolean space= true;
int i;
for ( i = 0; i < str1.length(); i++) {
if (str1.charAt(i) == ' ') {
space=true;
} else {
i++;
}
}
System.out.println("there are " + i + " letters");
}
}

Categories

Resources