Code to tell whether a string is a Pangram or not? - java

import java.io.*;
import java.util.*;
public class Solution {
public static final int n = 26;
public int check(String arr) {
if (arr.length() < n) {
return -1;
}
for (char c = 'A'; c <= 'Z'; c++) {
if ((arr.indexOf(c) < 0) && (arr.indexOf((char)(c + 32)) < 0)) {
return -1;
}
}
return 1;
}
}
public static void main(String[] args) {
Scanner s1 = new Scanner(System.in);
String s = s1.next();
Solution obj = new Solution();
int d = obj.check(s);
if (d == -1) {
System.out.print("not pangram");
} else {
System.out.print("pangram");
}
}
If the string entered is:
We promptly judged antique ivory buckles for the next prize
It will give the wrong output:
not pangram.
I'm not able to find out what wrong with the code.
Thanks in advance!

The problem is that whitespace is a separator for Scanner.next(). So when you input We promptly judged antique ivory buckles for the next prize, s will point just to the string We. When you call obj.check(s) on We it will return -1.
To verify that this is the case, you can print s and check its value. You can also do:
String s = "We promptly judged antique ivory buckles for the next prize";
Call obj.check(s) and see that it will return the correct answer.
To fix it you should call Scanner.nextLine() instead of Scanner.next():
String s = s1.nextLine();

May be program by using set will make solution easier ..:)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
public class Pangram {
public static void main(String args[]) {
try {
final String str;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
str = br.readLine().toLowerCase().replaceAll(" ", "");
char[] chars = str.toCharArray();
final Set set = new HashSet();
for(char c: chars){
set.add(c);
}
System.out.println(set.size());
if(set.size() == 26)
System.out.println("pangram");
else
System.out.println("not pangram");
} catch (Exception e) {
e.printStackTrace();
}
}
}

Another version:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String sentence = scan.nextLine();
sentence = sentence.toUpperCase();
sentence = sentence.replaceAll("[^A-Z]", "");
char[] chars = sentence.toCharArray();
Set<Character> set = new HashSet<Character>();
for( int i = 0; i < chars.length; i++ ) set.add(chars[i]);
System.out.println(set.size() == 26 ? "pangram" : "not pangram");
}
}

Another Similar Solution for your problem.
public class PangramExample {
public static void main(String[] args) {
String s = "The quick brown fox jumps over the lazy dog";
System.out.println("Is given String Pangram ? : "
+ isPangramString(s.toLowerCase()));
}
private static boolean isPangramString(String s) {
if (s.length() < 26)
return false;
else {
for (char ch = 'a'; ch <= 'z'; ch++) {
if (s.indexOf(ch) < 0) {
return false;
}
}
}
return true;
}
}
for reference , refer this link http://techno-terminal.blogspot.in/2015/11/java-program-to-check-if-given-string.html

import java.io.;
import java.util.;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
System.out.println(isPangram(input) ? "pangram" : "not pangram");
}
static boolean isPangram(String input) {
boolean isPangram = false;
if(input == null || input.length() < 26) {
return isPangram;
}
input = input.toLowerCase();
char [] charArray = input.toCharArray();
Set<Character> charSet = new HashSet<>();
for(char c : charArray) {
if(Character.isLetter(c) && (!Character.isWhitespace(c))) {
charSet.add(c);
}
}
if (charSet.size() == 26) {
isPangram = true;
}
return isPangram;
}
}

import java.util.Scanner;
public class Pangrams {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
int[] a = new int[26];
int count =0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)>=65 && s.charAt(i)<=90){
if(a[s.charAt(i)-65]==0)
count++;
a[s.charAt(i)-65]++;
}
else if(s.charAt(i)>=97 && s.charAt(i)<=122){
if(a[s.charAt(i)-97]==0)
count++;
a[s.charAt(i)-97]++;
}
}
if(count==26)
System.out.println("pangram");
else
System.out.println("not pangram");
}
}

This should fix it:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static boolean isPangram(String test){
for (char a = 'A'; a <= 'Z'; a++)
if ((test.indexOf(a) < 0) && (test.indexOf((char)(a + 32)) < 0))
return false;
return true;
}
public static void main(String[] args)throws IOException {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String test=br.readLine();
if(isPangram(test.toUpperCase())){
System.out.println("pangram");
}if(isPangram(test.toUpperCase())==false){
System.out.println("not pangram");
}
}
}

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
String s;
char f;
Scanner in = new Scanner(System.in);
s = in.nextLine();
char[] charArray = s.toLowerCase().toCharArray();
final Set set = new HashSet();
for (char a : charArray) {
if ((int) a >= 97 && (int) a <= 122) {
f = a;
set.add(f);
}
}
if (set.size() == 26){
System.out.println("pangram");
}
else {
System.out.println("not pangram");
}
}
}

import java.util.Scanner;
public class Pangram {
public static void main(String[] args) {
int count=0;//Initialize counter to zero
char[] arr = new char[26];//Character array of 26 size as there are 26 alphabets
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
for(int i= 0; i<s.length();i++)
{
if(s.charAt(i)>=65 && s.charAt(i)<=90)//Ascii value of A to Z(caps)
{
if(arr[s.charAt(i)-65]==0)
{
count++;
arr[s.charAt(i)-65]=1;
}
}
if(s.charAt(i)>=97 && s.charAt(i)<=122)//Ascii value of a to z
{
if(arr[s.charAt(i)-97]==0)
{
count++;
arr[s.charAt(i)-97]=1;
}
}
}
System.out.println(count);
if(count==26)
{
System.out.println("Pangram");
}
else
System.out.println("not Pangram");
}
}

Another approach of doing this
public boolean isPanGram(String arg)
{
String temp = arg.toLowerCase().replaceAll(" ", "");
String str = String.valueOf(temp.toCharArray());
String[] array = str.split("");
Set<String> tempSet = new TreeSet(Arrays.asList(array));
if(tempSet.size()==26)
{
List loopList = new ArrayList();
loopList.addAll(tempSet);
if(loopList.get(0).equals("a") && loopList.get(25).equals("z"))
return true;
}
return false;
}

Try it
static String pangrams(String s) {
String result="";
String ls = s.toLowerCase();
HashSet<Character> ts=new HashSet<Character>();
for(int i=0;i<ls.length();i++){
if(ls.charAt(i)!=' '){
ts.add(ls.charAt(i));
}
}
if(ts.size()==26){
result="pangram";
}
else{
result="not pangram";
}
return result;
}

Another simple program using HashSet collection.
import java.util.HashSet;
public class Panagram {
public static void main(String[] args) {
pangrams("qmExzBIJmdELxyOFWv LOCmefk TwPhargKSPEqSxzveiun");
}
static String pangrams(String s) {
String inputString = s.toLowerCase();
HashSet<String> toRemoveDuplicates = new HashSet<String>();
for (String eachAlphabet : inputString.split("")) {
toRemoveDuplicates.add(eachAlphabet);
}
// Total alphabets are 26 + one space, so 27.
if (toRemoveDuplicates.size() == 27)
return "panagram";
else
return "not panagram";
}
}

This is a different approach, but easy to understand and write.
First remove all punctuation/whitespace, then drop all duplicated letters.
Finally make sure the modified string has exactly 26 letters.
public class Pangrams {
public static void main(String[] args) {
String s = "The quick brown fox jumps over the lazy dog" //any text
.replaceAll("[^a-zA-Z]+", "") //remove all punctuation and whitespace
if (s.length() < 1 || s.length() > 100)
System.exit(0);
boolean isPangram = false;
char ch;
String modifiedStr = "";
//remove all duplicate letters
for (int i = 0; i < s.length(); i++) {
ch = s.charAt(i);
if (ch != ' ') {
modifiedStr += ch;
s = s.replace(ch, ' ');
}
}
//check whether it has exactly 26 letters
if (modifiedStr.length() == 26) {
isPangram = true;
System.out.println("I am a pangram");
}
else System.out.println("I am not a pangram");
}
}

plain Java for loop to detect if string is Pangram:
for (char c = 'a'; c <= 'z'; c++)
if (str.toLowerCase().indexOf(c)== -1)
return false;

Here's a more straight forward approach. It also takes into consideration the repetition of letters, numbers of spaces, tabs and all. You can actually work out with real time sentences. And also if you are a newbie, you won't find this code hard to understand (or i hope so) :)
import java.io.*;
import java.util.*;
public class Solution{
static boolean check(String str){
str=str.toUpperCase();
int count=0;
for(char c='A';c<='Z';c++){
if( (str.indexOf(c)>=0) )
count++;
}
if(count ==26)
return true;
else
return false;
}
public static void main(String args[]){
Scanner scan=new Scanner(System.in);
String s=scan.nextLine();
if(check(s))
System.out.println("pangram");
else
System.out.println("not pangram");
}
}

public class Panagram
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter string ");
String s = sc.nextLine();
System.out.println("given string is :"+"\n" +s);
String st=removeSpace(s);
int d = check(st);
if(d == -1)
System.out.print(s+"\n" + "is not pangram");
else
System.out.print(s+"\n" +"is a pangram");
}
public static String removeSpace(String s)
{
char ch[]=s.toCharArray();
String nstr="";
for (int i = 0; i < s.length(); i++)
{
if (ch[i]!=' ')
{
nstr=nstr + ch[i];
}
}
return nstr;
}
public static int check(String st)
{
int n = 26;
if(s.length() < n){
return -1; }
for(char i = 'A'; i <= 'Z' ; i++){
if((st.indexOf(i) < 0) && (st.indexOf((char)(i + 32)) < 0))

Related

How can you rearrange characters to make a word existing in the dictionary?

I've been trying to tweak little bits of code here and there to make my output correct. I am trying to have my code be able to rearrange the letters in a word to make other words that exist in words.txt, from https://github.com/dwyl/english-words. Any help would be appreciated. Thanks.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class WordsInWords {
public static void main(String[] args) throws IOException {
String file = "/Users/laptop/Desktop/Test.txt";
BufferedReader r = new BufferedReader(new FileReader(file));
StringBuilder b = new StringBuilder();
String c = r.readLine();
while (c != null) {
b.append(c);
b.append(" ");
c = r.readLine();
}
Scanner s = new Scanner(System.in);
String in = s.nextLine();
char[] input = new char[in.length()];
for (int i = 0; i < input.length; i++) {
input[i] = in.charAt(i);
}
char[] temp = null;
for (int i = 0; i < b.length(); i++) {
if (i < b.length() - 1 && b.charAt(i) == ' ' && b.charAt(i + 1) != ' ') {
boolean found = false;
int counter = 0;
while (!found) {
counter++;
if (b.charAt(i + counter) == ' ') {
found = true;
temp = new char[counter - 1];
for (int j = i + 1; j < i + counter; j++) {
temp[j] = b.charAt(j);
}
}
}
}
}
if (Arrays.asList(input).contains(temp)) {
System.out.println(temp);
}
}
}
Here is my tweaked code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class WordsInWords {
public static void main(String[] args) throws IOException {
String file = "/Users/laptop/Desktop/words.txt";
BufferedReader r = new BufferedReader(new FileReader(file));
String[] words;
String c = r.readLine();
int a=0;
while (c != null) {
c = r.readLine();
a++;
}
words=new String[a];
a=0;
r = new BufferedReader(new FileReader(file));
String temp=r.readLine();
while (temp != null) {
words[a]=r.readLine();
temp=words[a];
a++;
}
for (int i = 0; i < words.length; i++) {
System.out.println(words[i]);
}
Scanner s = new Scanner(System.in);
String input = s.nextLine();
List<String> found = findRearranged(input, words);
System.out.println("For '" + input + "' found: " + Arrays.toString(found.toArray()));
}
public static List<String> findRearranged(String input, String[] words) {
List<String> found = new ArrayList<>();
for (String w : words) {
if (hasSameLetters(w, input)) {
found.add(w);
}
}
return found;
}
public static boolean hasSameLetters(String a, String b) {
if (a.length() != b.length()) {
return false;
}
while (a.length() > 0) {
for (char c : b.toCharArray()) {
int index = a.indexOf(c);
if (index >= 0) {
a = a.replace(String.valueOf(c), "");
} else {
return false;
}
}
}
return true;
}
}
Is rearranging the characters necessary?
Rearranging the input and searching through dictionary to find equal word could take lot's of computing time, single few letter word can have many permutations.
For me, it looks like you want to find the words in dictionary for input word containing same letters (in other words, if the input word would be rearranged, it would give you the existing word in dictionary). Probably checking if both words are having exactly same letters, regardless their position in both strings should satisfy the requirement.
Here's the sample for that approach:
public class Sample {
public static void main(String[] args) {
//the words in dictionary
String[] words = {"words", "sword", "nord", "chord", "score", "cores", "mors", "xyz", "scores", "ordsw"};
String[] input = {"sword", "score", "tores", "nores"};
for (String i : input) {
List<String> found = findRearranged(i, words);
System.out.println("For '" + i + "' found: " + Arrays.toString(found.toArray()));
}
}
public static List<String> findRearranged(String input, String[] words) {
List<String> found = new ArrayList<>();
for (String w : words) {
if (hasSameLetters(w, input)) {
found.add(w);
}
}
return found;
}
public static boolean hasSameLetters(String a, String b) {
if (a.length() != b.length()) {
return false;
}
while (a.length() > 0) {
for (char c : b.toCharArray()) {
int index = a.indexOf(c);
if (index >= 0) {
a = a.replace(String.valueOf(c), "");
} else {
return false;
}
}
}
return true;
}
}
And this outputs in:
For 'sword' found: [words, sword, ordsw]
For 'score' found: [score, cores]
For 'tores' found: []
For 'nores' found: []
Edit:
I see the assumption is that every word is in its own line.
I saw that you already came up with counting the words in the file, but still in that case it's better to use Collections which are having dynamic size.
Here's fixed sample:
public class WordsInWords {
public static void main(String[] args) throws IOException {
String file = "C:\\Users\\masta\\IdeaProjects\\podstawka-spring-java\\words.txt";
BufferedReader r = new BufferedReader(new FileReader(file));
List<String> words = new ArrayList<>();
String c = r.readLine();
while (c != null) {
words.add(c);
c = r.readLine();
}
for (int i = 0; i < words.size(); i++) {
System.out.println("Words: " + words.get(i));
}
Scanner s = new Scanner(System.in);
String input = s.nextLine();
List<String> found = findRearranged(input, words);
System.out.println("For '" + input + "' found: " + Arrays.toString(found.toArray()));
}
public static List<String> findRearranged(String input, List<String> words) {
List<String> found = new ArrayList<>();
for (String w : words) {
if (hasSameLetters(w, input)) {
found.add(w);
}
}
return found;
}
public static boolean hasSameLetters(String a, String b) {
if (a.length() != b.length()) {
return false;
}
while (a.length() > 0) {
for (char c : b.toCharArray()) {
int index = a.indexOf(c);
if (index >= 0) {
a = a.replace(String.valueOf(c), "");
} else {
return false;
}
}
}
return true;
}
}

Problem with Java code that will print TRUE when a word has no vowels in an IF statement

I am trying to write a code the will print TRUE when i enter a word with no vowels and will print FALSE if I enter a word with vowels. I am having trouble when it comes to writing the string. I give one of the strings the value that holds all the values.
String A = "aeiou";
The other 2 strings hold the rest of the alphabet.
When I type in a word that has vocals it prints FALSE however when I type in a word with no vowels it prints FALSE.
I wanna know if there is a way to make the program read the values of the string as separate entities and not as a whole line.
package lab3;
import java.util.Scanner;
public class Lab3 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String input = reader.next();
/* A and B, but not C */
String A = "bcdfghjklm";
String B = "npqrstvwxyz";
String C = "aeiou";
if (input.contains(A) && input.contains(B) || input.contains(C)) {
System.out.println("TRUE");
} else {
System.out.println("FALSE");
}
}
}
You can do it with a short function
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String input = reader.next();
System.out.println(chk(input));
}
static public boolean chk(String s) {
for (int i = 0; i < s.length(); i++) {
if ("aeiou".indexOf(s.charAt(i)) != -1) {
return false;
}
}
return true;
}
}
This is a working correct for your purpose:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String input = reader.next();
String C = "aeiou";
for (int i = 0; i < input.length(); i++) {
char inputA = input.charAt(i);
for (int j = 0; j < C.length(); j++) {
char c = C.charAt(j);
if (inputA == c) {
System.out.println("TRUE");
return;
}
}
}
System.out.println("FALSE");
}
The key point is to use the method charAt(int index); so you can check each char in the string.
You can choose to use any of the below two methods, containsVowel and containsVowel1 as both of them do the same thing:
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a text: ");
String input = reader.nextLine();
String[] vowels = { "a", "e", "i", "o", "u" };
System.out.println(!containsVowel(input, vowels));
System.out.println(!containsVowel1(input, vowels));
}
public static boolean containsVowel(String input, String[] vowels) {
return Arrays.stream(vowels).parallel().anyMatch(input::contains);
}
public static boolean containsVowel1(String input, String[] vowels) {
for (int i = 0; i < vowels.length; i++) {
if (input.contains(vowels[i])) {
return true;
}
}
return false;
}
}

The requirement is, the output will print one number followed by a character then a number and so on

I have am assignment suppose there is a string 11234aBcD the out put should be 1a1B2c3D4 and I am unable to do it, First and the second output I have done. And I have to do using java.
I am adding my code:
package Testx;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Test3optmz {
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner gaba = new Scanner( System.in );
String variable;
System.out.print("Enter String:");
variable = gaba.nextLine();
SeparateGaba(variable);
}
public static void SeparateGaba(String str)
{
String Catch_num = "";
String Catch_let = "";
String upper="";
String lower="";
String holdl="";
String holdn="";
for (int i = 0; i < str.length(); i++)
{
char a = str.charAt(i);
if (Character.isDigit(a))
{
Catch_num = Catch_num + a;
} else
{
Catch_let = Catch_let + a;
}
}
System.out.println("FIRST OUTPUT:"+Catch_num+Catch_let);// i am separating the numbers and alphabets
for(int j=0;j <Catch_let.length();j++)
{
char x = Catch_let.charAt(j);
if (Character.isUpperCase(x))
{
upper += x;
}
else
{
lower += x;
}
}
char[] num = Catch_num.toCharArray();
Arrays.sort(num);
String n =new String(num);
char[] ordr = lower.toCharArray();
Arrays.sort(ordr);
String alfa1 =new String(ordr);
char[] ord = upper.toCharArray();
Arrays.sort(ord);
String alfa =new String(ord);
String t= alfa1 + alfa;
char [] fin = t.toCharArray();
Arrays.sort(fin);
String fal = new String(fin);
Character[] chars = new Character[fal.length()];
for (int f=0; f < fal.length();f++)
chars[f] = fal.charAt(f);
Arrays.sort(chars, new Comparator<Character>()
{
public int compare(Character c1, Character c2)
{
int cmp = Character.compare(
Character.toLowerCase(c1.charValue()),
Character.toLowerCase(c2.charValue())
);
if (cmp != 0) return cmp;
return Character.compare(c1.charValue(), c2.charValue());
}
});
StringBuilder sb = new StringBuilder(chars.length);
for (char c : chars) sb.append(c);
fal = sb.toString();
System.out.println("SECOND OUTPUT= "+n+fal);// now i am arranging the alphabet in ascending order avoiding capital and small ex 1234eBaC it will come as 1234aBce
}
}
well thanks for not helping me out i helped my self
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class Test4 {
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner gaba = new Scanner( System.in );
String variable;
System.out.print("Enter String:");
variable = gaba.nextLine();
SeparateGaba(variable);
}
public static void SeparateGaba(String str)
{
String Catch_num = "";
String Catch_let = "";
String upper="";
String lower="";
for (int i = 0; i < str.length(); i++)
{
char a = str.charAt(i);
if (Character.isDigit(a))
{
Catch_num = Catch_num + a;
} else
{
Catch_let = Catch_let + a;
}
}
System.out.println("FIRST OUTPUT:"+Catch_num+Catch_let);
for(int j=0;j <Catch_let.length();j++)
{
char x = Catch_let.charAt(j);
if (Character.isUpperCase(x))
{
upper += x;
}
else
{
lower += x;
}
}
char[] num = Catch_num.toCharArray();
Arrays.sort(num);
String n =new String(num);
char[] ordr = lower.toCharArray();
Arrays.sort(ordr);
String alfa1 =new String(ordr);
char[] ord = upper.toCharArray();
Arrays.sort(ord);
String alfa =new String(ord);
String t= alfa1 + alfa;
char [] fin = t.toCharArray();
Arrays.sort(fin);
String fal = new String(fin);
Character[] chars = new Character[fal.length()];
for (int f=0; f < fal.length();f++)
chars[f] = fal.charAt(f);
Arrays.sort(chars, new Comparator<Character>()
{
public int compare(Character c1, Character c2)
{
int cmp = Character.compare(
Character.toLowerCase(c1.charValue()),
Character.toLowerCase(c2.charValue())
);
if (cmp != 0) return cmp;
return Character.compare(c1.charValue(), c2.charValue());
}
});
StringBuilder sb = new StringBuilder(chars.length);
for (char c : chars) sb.append(c);
fal = sb.toString();
System.out.println("SECOND OUTPUT= "+n+fal);
/*GABA come on let seeeeeeeee*/
try
{
for(int i=0;i<n.length();i++)
{
char a= n.charAt(i);
System.out.print(a);
for(int j=0; j<fal.length();j++)//1
{
char b = fal.charAt(j);
if(j>=i)
{
System.out.print(b);
break;
}
}
}
}
catch(Exception e)
{
System.out.println("Your letter length should match with char len");
}
}
}
Enter String:14a5Bc
FIRST OUTPUT:145aBc
SECOND OUTPUT= 145aBc
THE out put i was looking for --->1a4B5c

Splitting a sentence into words using for loop or while loop in java

i have to do a program which takes a sentence and reverses it word by word in java. for eg:
India is my country
output:aidnI si ym yrtnuoc
ive figured out all of it but i just cant split a sentence into separate words.im not allowed to use split function but im meant to use either substring or indexof();while loop and for loop are allowed.
this is what ive got so far:
import java.io.*;
public class Rereprogram10
{
public void d()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("input a string");
str=br.readLine();
String rev="";
int length=str.length();
int counter=length;
for(int i=0;i<length;i++)
{
rev=rev+str.charAt(counter-1);
counter--;
}
System.out.println("the result is: "+rev);
}
}
its wrong though,the output keeps on coming:
yrtnuoc ym si aidnI
i havent learnt arrays yet...
I'm going to assume that advanced datastructures are out, and efficiency is not an issue.
Where you are going wrong is that you are reversing the entire string, you need to only reverse the words. So you really need to check to find where a word ends, then either reverse it then, or be reversing it as you go along.
Here is an example of reversing as you go along.
int length=str.length();
String sentence="";
String word = "";
for(int i=0;i<length;i++) {
if (str.charAt(i) != ' '){
word = str.charAt(i) + word;
} else {
sentence += word +" ";
word = "";
}
}
sentence += word;
System.out.println("the result is: "+sentence);
This passes the test:
package com.sandbox;
import com.google.common.base.Joiner;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class SandboxTest {
#Test
public void testQuestionInput() {
String input = "India is my country";
assertEquals("country my is India", reverseWords(input));
}
private String reverseWords(String input) {
List<String> words = putWordsInList(input);
Collections.reverse(words);
return Joiner.on(" ").join(words);
}
private List<String> putWordsInList(String input) {
List<String> words = new ArrayList<String>();
String word = "";
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c == ' ') {
words.add(word);
word = "";
} else {
word += c;
}
}
words.add(word);
return words;
}
}
Here is my code without split() for you.
Input:
India is my country
Output:
country my is India
aidnI si ym yrtnuoc
You can choose the output you need.
public class Reverse {
public static class Stack {
private Node[] slot = new Node[1000];
private int pos = 0;
private class Node{
private char[] n = new char[30];
private int pos = 0;
public void push(char c) {
n[pos++] = c;
}
public String toString() {
return new String(n).trim() + " "; // TODO Fix
}
}
public void push(char c) {
if(slot[pos] == null)
slot[pos] = new Node();
if(c != ' ') {
slot[pos].push(c);
} else {
slot[pos++].push(c);
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
for(int i = pos; i >=0; i --)
sb.append(slot[i]);
return sb.toString();
}
private String reverseWord(String word) {
StringBuilder sb = new StringBuilder();
int len = word.length();
for(int i = len - 1; i >= 0; i--)
sb.append(word.charAt(i));
return sb.toString();
}
public String foryou() {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < pos + 1; i ++)
sb.append(this.reverseWord(slot[i].toString()));
return sb.toString();
}
}
/**
* #param args
*/
public static void main(String[] args) {
Stack stack = new Stack();
String sentence = "India is my country";
System.out.println(sentence);
for(int i = 0; i < sentence.length(); i ++) {
stack.push(sentence.charAt(i));
}
System.out.println(stack);
System.out.println(stack.foryou());
}
}
try this
String x="India is my country";
StringBuilder b=new StringBuilder();
int i=0;
do{
i=x.indexOf(" ", 0);
String z;
if(i>0){
z=x.substring(0,i);
}
else{
z=x;
}
x=x.substring(i+1);
StringBuilder v=new StringBuilder(z);
b.append(v.reverse());
if(i!=-1)
b.append(" ");
System.out.println(b.toString());
}
while(i!=-1);

Count words in a string method?

I was wondering how I would write a method to count the number of words in a java string only by using string methods like charAt, length, or substring.
Loops and if statements are okay!
I really appreciate any help I can get! Thanks!
This would work even with multiple spaces and leading and/or trailing spaces and blank lines:
String trim = s.trim();
if (trim.isEmpty())
return 0;
return trim.split("\\s+").length; // separate string around spaces
More info about split here.
public static int countWords(String s){
int wordCount = 0;
boolean word = false;
int endOfLine = s.length() - 1;
for (int i = 0; i < s.length(); i++) {
// if the char is a letter, word = true.
if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
word = true;
// if char isn't a letter and there have been letters before,
// counter goes up.
} else if (!Character.isLetter(s.charAt(i)) && word) {
wordCount++;
word = false;
// last word of String; if it doesn't end with a non letter, it
// wouldn't count without this.
} else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}
Hi I just figured out with StringTokenizer like this:
String words = "word word2 word3 word4";
StringTokenizer st = new Tokenizer(words);
st.countTokens();
Simply use ,
str.split("\\w+").length ;
public static int countWords(String str){
if(str == null || str.isEmpty())
return 0;
int count = 0;
for(int e = 0; e < str.length(); e++){
if(str.charAt(e) != ' '){
count++;
while(str.charAt(e) != ' ' && e < str.length()-1){
e++;
}
}
}
return count;
}
private static int countWordsInSentence(String input) {
int wordCount = 0;
if (input.trim().equals("")) {
return wordCount;
}
else {
wordCount = 1;
}
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
String str = new String("" + ch);
if (i+1 != input.length() && str.equals(" ") && !(""+ input.charAt(i+1)).equals(" ")) {
wordCount++;
}
}
return wordCount;
}
Use
myString.split("\\s+");
This will work.
There is a Simple Solution You can Try this code
String s = "hju vg jhdgsf dh gg g g g ";
String[] words = s.trim().split("\\s+");
System.out.println("count is = "+(words.length));
public static int countWords(String input) {
int wordCount = 0;
boolean isBlankSet = false;
input = input.trim();
for (int j = 0; j < input.length(); j++) {
if (input.charAt(j) == ' ')
isBlankSet = true;
else {
if (isBlankSet) {
wordCount++;
isBlankSet = false;
}
}
}
return wordCount + 1;
}
Algo in O(N)
count : 0;
if(str[0] == validChar ) :
count++;
else :
for i = 1 ; i < sizeOf(str) ; i++ :
if(str[i] == validChar AND str[i-1] != validChar)
count++;
end if;
end for;
end if;
return count;
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));
}
add at the pom.xml
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>r09</version>
</dependency>
Counting Words in a String:
This might also help -->
package data.structure.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CountWords {
public static void main(String[] args) throws IOException {
// Couting number of words in a string
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter Your String");
String input = br.readLine();
char[] arr = input.toCharArray();
int i = 0;
boolean notCounted = true;
int counter = 0;
while (i < arr.length) {
if (arr[i] != ' ') {
if (notCounted) {
notCounted = false;
counter++;
}
} else {
notCounted = true;
}
i++;
}
System.out.println("words in the string are : " + counter);
}
}
public class TestStringCount {
public static void main(String[] args) {
int count=0;
boolean word= false;
String str = "how ma ny wo rds are th ere in th is sente nce";
char[] ch = str.toCharArray();
for(int i =0;i<ch.length;i++){
if(!(ch[i]==' ')){
for(int j=i;j<ch.length;j++,i++){
if(!(ch[j]==' ')){
word= true;
if(j==ch.length-1){
count++;
}
continue;
}
else{
if(word){
count++;
}
word = false;
}
}
}
else{
continue;
}
}
System.out.println("there are "+(count)+" words");
}
}
import java.util.;
import java.io.;
public class Main {
public static void main(String[] args) {
File f=new File("src/MyFrame.java");
String value=null;
int i=0;
int j=0;
int k=0;
try {
Scanner in =new Scanner(f);
while(in.hasNextLine())
{
String a=in.nextLine();
k++;
char chars[]=a.toCharArray();
i +=chars.length;
}
in.close();
Scanner in2=new Scanner(f);
while(in2.hasNext())
{
String b=in2.next();
System.out.println(b);
j++;
}
in2.close();
System.out.println("the number of chars is :"+i);
System.out.println("the number of words is :"+j);
System.out.println("the number of lines is :"+k);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
My idea of that program is that:
package text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CoutingWords {
public static void main(String[] args) throws IOException {
String str;
int cWords = 1;
char ch;
BufferedReader buffor = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter text: ");
str = buffor.readLine();
for(int i =0; i<str.length(); i++){
ch = str.charAt(i);
if(Character.isWhitespace(ch)){ cWords++; }
}
System.out.println("There are " + (int)cWords +" words.");
}
}
I'm new to stackoverflow but I hope my code helps:
private int numOfWordsInLineCounter(String line){
int words = 0;
for(int i = 1 ; i<line.length();i++){
Character ch = line.charAt(i-1);
Character bch = line.charAt(i);
if(Character.isLetterOrDigit(ch) == true && Character.isLetterOrDigit(bch)== false ) words++;
if(i == line.length()-1 && Character.isLetterOrDigit(bch))words++;
}
return words;
}
A string phrase normaly has words separated by space. Well you can split the phrase using the spaces as separating characters and count them as follows.
import java.util.HashMap;
import java.util.Map;
public class WordCountMethod {
public static void main (String [] args){
Map<String, Integer>m = new HashMap<String, Integer>();
String phrase = "hello my name is John I repeat John";
String [] array = phrase.split(" ");
for(int i =0; i < array.length; i++){
String word_i = array[i];
Integer ci = m.get(word_i);
if(ci == null){
m.put(word_i, 1);
}
else m.put(word_i, ci+1);
}
for(String s : m.keySet()){
System.out.println(s+" repeats "+m.get(s));
}
}
}
Taking the chosen answer as a starting point the following deals with a few English language issues including hyphenated words, apostrophes for possessives and shortenings, numbers and also any characters outside of UTF-16:
public static int countWords(final String s) {
int wordCount = 0;
boolean word = false;
final int endOfLine = s.length() - 1;
for (int i = 0; i < s.length(); i++) {
// if the char is a letter, word = true.
if (isWordCharacter(s, i) && i != endOfLine) {
word = true;
// if char isn't a letter and there have been letters before,
// counter goes up.
} else if (!isWordCharacter(s, i) && word) {
wordCount++;
word = false;
// last word of String; if it doesn't end with a non letter, it
// wouldn't count without this.
} else if (isWordCharacter(s, i) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}
private static boolean isWordCharacter(final String s, final int i) {
final char ch = s.charAt(i);
return Character.isLetterOrDigit(ch)
|| ch == '\''
|| Character.getType(ch) == Character.DASH_PUNCTUATION
|| Character.isSurrogate(ch);
}
I just put this together. The incrementer in the wordCount() method is a bit inelegant to me, but it works.
import java.util.*;
public class WordCounter {
private String word;
private int numWords;
public int wordCount(String wrd) {
StringTokenizer token = new StringTokenizer(wrd, " ");
word = token.nextToken();
numWords = token.countTokens();
numWords++;
return numWords;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userWord;
WordCounter wc = new WordCounter();
System.out.println("Enter a sentence.");
userWord = input.nextLine();
wc.wordCount(userWord);
System.out.println("You sentence was " + wc.numWords + " words long.");
}
}
create variable count, state. initialize variables
if space is present keep count as it is else increase count.
for eg:
if (string.charAt(i) == ' ' ) {
state = 0;
} else if (state == 0) {
state = 1;
count += 1;
lambda, in which splitting and storing of the counted words is dispensed withand only counting is done
String text = "counting w/o apostrophe's problems or consecutive spaces";
int count = text.codePoints().boxed().collect(
Collector.of(
() -> new int[] {0, 0},
(a, c) -> {
if( ".,; \t".indexOf( c ) >= 0 )
a[1] = 0;
else if( a[1]++ == 0 ) a[0]++;
}, (a, b) -> {a[0] += b[0]; return( a );},
a -> a[0] ) );
gets: 7
works as a status machine that counts the transitions from spacing characters .,; \t to words
if(str.isEmpty() || str.trim().length() == 0){
return 0;
}
return (str.trim().split("\\s+").length);
String a = "Some String";
int count = 0;
for (int i = 0; i < a.length(); i++) {
if (Character.isWhitespace(a.charAt(i))) {
count++;
}
}
System.out.println(count+1);
It will count white spaces. However, If we add 1 in count , we can get exact words.

Categories

Resources