Word count from text - java

This is my code to work out the length of a word:
public class WordCount {
public static void main (String args []) {
String text;
text = "Java";
System.out.println (text);
//Work out the length
String [] input = text.split(" ");
int MaxWordLength = 0;
int WordLength = 0;
for (int i = 0; i < input.length; i++)
{
MaxWordLength = input[i].length();
WordLength = MaxWordLength;
} //End of working out length
//Work out no. of words
int[] intWordCount = new int[WordLength + 1];
for(int i = 0; i < input.length; i++) {
intWordCount[input[i].length()]++; }
for (int i = 1; i < intWordCount.length; i++) {
System.out.println("There are " + intWordCount[i] + " words of length " + MaxWordLength);
}
}
}
The problem I am having is that when it prints out the length of the word, I get these results:
Java
There are 0 words of length 4
There are 0 words of length 4
There are 0 words of length 4
There are 1 words of length 4
But when I change the text to "J" this prints out:
J
There are 1 words of length 1
Any idea why it's doing that?
P.S. I'm kind of new to Java and any help would be appreciated.

I am not sure if you want to count letter or word because your code counts letter to me.
Just you need to change this line from
String [] input = text.split(" ");
to
String [] input = text.split("");
and your program works perfectly.
input: Java
output: There are 4 letters of length 1 <- Hope this is the expected result for you
Source: Splitting words into letters in Java
You can achieve this in better and less headache by using Lambda in Java
Code:
import java.util.*;
public class LambdaTest
{
public static void main (String[] args)
{
String[] st = "Hello".split("");
Collection myList = Arrays.asList(st);
System.out.println("your word has " + myList.stream().count() + "letters");
}
}
Output:
your word has 5 letters CLEARLY in length 1
My answer when you cleared what your issue is
Code:
public class WordCount
{
public static void main (String[] args)
{
String text ="";
int wordLenght = 0;
text = "Java is awesome for Me";
System.out.println (text);
String [] input = text.split(" ");
List<Integer> list = new ArrayList<>();
for (int i = 0; i < input.length; i++)
{
list.add(input[i].length());
}
Set<Integer> unique = new HashSet<Integer>(list);
for (Integer length : unique) {
System.out.println("There are " + Collections.frequency(list, length) + " words of length " + length);
}
}
}
output:
There are 2 words of length 2
There are 1 words of length 3
There are 1 words of length 4
There are 1 words of length 7
Note: Read about HashSet and Set in Java
Source: http://javarevisited.blogspot.com/2012/06/hashset-in-java-10-examples-programs.html

Let's walk through this:
public class WordCount {
public static void main (String args []) {
String text;
text = "Java";
text is equal to "Java".
System.out.println (text);
Prints "Java"
//Work out the length
String [] input = text.split(" ");
This splits the string "Java" on spaces, of which there are none. So input (which I'd recommend be renamed to something more indicative, like inputs) is equal to an array of one element, and that one element is equal to "Java".
int MaxWordLength = 0;
int WordLength = 0;
for (int i = 0; i < input.length; i++)
{
MaxWordLength = input[i].length();
For each element, of which there is only one, MaxWordLength is set to the length of the first (and only) element, which is "Java"...whose length is 4.
WordLength = MaxWordLength;
So WordLength is now equal to 4.
} //End of working out length
//Work out no. of words
int[] intWordCount = new int[WordLength + 1];
This creates an int array of [WordLength + 1] elements (which is equal to [4 + 1], or 5), where each is initialized to zero.
for(int i = 0; i < input.length; i++) {
intWordCount[input[i].length()]++; }
For each element in input, of which there is only one, this sets the input[i].length()-th element--the fifth, since input[i] is "Java" and it's length is four--to itself, plus one (because of the ++).
Therefore, after this for loop, the array is now equal to [0, 0, 0, 0, 1].
for (int i = 1; i < intWordCount.length; i++) {
System.out.println("There are " + intWordCount[i] + " words of length " + MaxWordLength);
So this naturally prints the undesired output.
}
}
}
Your output is different when the input is only "J", because the intWordCount array is shortened to input[i].length() elements, which is now 1. But the value of the last element is still set to "itself plus one", and "itself" is initialized to zero (as all int-array elements are), and then incremented by one (with ++).

for (int i = 1; i < intWordCount.length; i++) {
System.out.println("There are " + intWordCount[i] + " words of length " + MaxWordLength);
}
1) You print out words with intWordCount[i] == 0, which is why you have the "There are 0 words of length X"
2) System.out.println("There are " ... + MaxWordLength); should probably be System.out.println("There are " ... + i);, so you have "There are 0 words of length 1" , "There are 0 words of length 2", etc

I know this question has been solved long time ago, but here is another solution using new features of Java 8. Using Java streams the whole exercise can be written in one line:
Arrays.asList(new String[]{"Java my love"}) //start with a list containing 1 string item
.stream() //start the stream
.flatMap(x -> Stream.of(x.split(" "))) //split the string into words
.map((String x) -> x.length()) //compute the length of each word
.sorted((Integer x, Integer y) -> x-y) //sort words length (not necessary)
.collect(Collectors.groupingBy(x -> x, Collectors.counting())) //this is tricky: collect results to a map: word length -> count
.forEach((x,y) -> {System.out.println("There are " + y + " word(s) with " + x + " letter(s)");}); //now print each result
Probably in few year time this would be a preferred method for solving such problems. Anyway it is worth knowing that such alternative exists.

To count words in text with we used Pattern class with while loop:
I. Case Sensitive word counts
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CountWordsInText {
public static void main(String[] args) {
String paragraph = "I am at office right now."
+ "I love to work at office."
+ "My Office located at center of kathmandu valley";
String searchWord = "office";
Pattern pattern = Pattern.compile(searchWord);
Matcher matcher = pattern.matcher(paragraph);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println(count);
}
}
II. Case Insensitive word counts
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CountWordsInTextCaseInsensitive {
public static void main(String[] args) {
String paragraph = "I am at office right now."
+ "I love to work at oFFicE."
+"My OFFICE located at center of kathmandu valley";
String searchWord = "office";
Pattern pattern = Pattern.compile(searchWord, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(paragraph);
int count = 0;
while (matcher.find())
count++;
System.out.println(count);
}
}

Idk, but using the length method as much as you have to figure out how the length mechanism works is like defining a word using the word. It's an honorable conquest figuring out how the length method works, but you should probably avoid using the length method.

Related

java swap last and 1st strings - problem works for 3 but not for 4

The code below works when number of strings in array is odd (3,5,7) however it does not work when the number is even. For example, if I use "my is the name" I get output
name is the name
public void randomTest() {
String str ="my is name";
//Step1: split so that I can get them in in array
String [] arrStr= str.split(" ");
for(int i=0;i<arrStr.length;i++){
//Step2: Using temp swap 1st and last
String temp = arrStr[0];
arrStr[0] = arrStr[arrStr.length-1];
arrStr[arrStr.length-1] = temp;
System.out.print(arrStr[i]+" ");
}
}
Any idea how can I make it work for even number of Strings? Thank You.
Since Arvind Kumar Avinash has shared the fixed solution, I just like to offer an alternative option: After splitting the string into String array, maybe you can simply swap the last and first values, and then join them together:
String str ="my is the name";
// split
String[] arrStr= str.split(" ");
// swap
String temp = arrStr[0];
arrStr[0] = arrStr[arrStr.length - 1];
arrStr[arrStr.length - 1] = temp;
// join them back
str = String.join(" ", arrStr);
System.out.println(str); // name is the my
You need to iterate the loop only for half of the length of the array i.e.
for (int i = 0; i < arrStr.length / 2; i++)
Also, you need to use the counter variable, i instead of the fixed values 0 and 1. Make sure to limit the indices in the range of 0 to length_of_array - 1 which is the range of indices of an array in Java.
Do it as follows:
public class Main {
public static void main(String[] args) {
String str = "my is the name";
String[] arrStr = str.split(" ");
// Swap the elements of the array
for (int i = 0; i < arrStr.length / 2; i++) {
String temp = arrStr[i];
arrStr[i] = arrStr[arrStr.length - i - 1];
arrStr[arrStr.length - i - 1] = temp;
}
// Display the array
for (int i = 0; i < arrStr.length; i++) {
System.out.print(arrStr[i] + " ");
}
}
}
Output:
name the is my
If you want to swap only the first word with the last word, you do not need a loop. You can simply so it as follows:
public class Main {
public static void main(String[] args) {
String str = "my is the name";
String[] arrStr = str.split(" ");
// Swap the first and the last words
String temp = arrStr[0];
arrStr[0] = arrStr[arrStr.length - 1];
arrStr[arrStr.length - 1] = temp;
// Display the array
for (int i = 0; i < arrStr.length; i++) {
System.out.print(arrStr[i] + " ");
}
}
}
Output:
name is the my
What you are currently doing is swapping the first and last elements n times, where n is the size of the array. This makes it so that when you have an even number of elements, for example, 2, then you are swapping the first and last elements, and then swapping them back to their original position, which is unswapped. This is also why it is working for an odd number of elements since you are swapping the first and last elements an even number of times and then once more. If you just want to swap the first and last elements, you can simply get rid of the for loop that you have and it will work properly.
public void randomTest() {
String str ="my is name";
//Step1: split so that I can get them in in array
String [] arrStr= str.split(" ");
//Step2: Using temp swap 1st and last
String temp = arrStr[0];
arrStr[0] = arrStr[arrStr.length-1];
arrStr[arrStr.length-1] = temp;
}
Afterwards, if you want to merge the strings back together, you can use
str = String.join(" ", arrStr);
or a StringBuilder object like so.
StringBuilder sb = new StringBuilder(arrStr[0]);
for (int i = 0; i < arrStr.length; i++) {
sb.append(" ").append(arrStr[i]);
}
str = sb.toString();
The effect of either of these will turn my name is foo into foo name is my, basically swapping the first and last words, and will work for a string with any length or number of words.
Easiest way is to substring first and last word from the sentence.
int first = name.indexOf(' '); // first "space" character that occurs
int last = name.lastIndexOf(' '); // last "space" character that occurs
String firstWord = name.substring(0, first); // substring first word from index 0 to index of first "space" character
String lastWord = name.substring(last, name.length()-1); // substring last word from index the of last "space" character to higher index o sentence
String midSentece = name.substring(first, last); // substring rest of the sentence
System.out.println(lastWord + midSentece + firstWord);

Is there a way to println to enumerate and list words in a string?

I'm trying to write a java program that will count the number of words in a declared sentence and then break the sentence up into words in order to list the words with numerical values and also display the words. I have the total count solved, but I can't seem to break up the words in the sentence and then list them chronologically. I can do it with characters, but not words.
I have explored both the Java Cookbook and other places to find a solution but I just do not understand it well enough. As I said, I can get the characters to count, and I can tally the words, but I can't get the individual words to print on separate lines with numerical values for their count in the string.
public class MySentenceCounter {
public static void main(String[] args) {
String sentence = "This is my sentence and it is not great";
String[] wordArray = sentence.trim().split("\\s+");
int wordCount = wordArray.length;
for (int i=0; i < sentence.length( ); i++)
System.out.println("Char " + i + " is " + sentence.charAt(i));
//this produces the character count but I need it to form words, not individual characters.
System.out.println("Total is " + wordCount + " words.");
}
}
Expected results should look like:
1 This
2 is
3 my
4 sentence
5 and
6 it
7 is
8 not
9 great
Total is 9 words.
Iterate over the wordArray variable you created rather than the original sentence string in your for loop:
public class MySentenceCounter {
public static void main(String[] args) {
String sentence = "This is my sentence and it is not great";
String[] wordArray = sentence.trim().split("\\s+");
// String[] wordArray = sentence.split(" "); This would work fine for your example sentence
int wordCount = wordArray.length;
for (int i = 0; i < wordCount; i++) {
int wordNumber = i + 1;
System.out.println(wordNumber + " " + wordArray[i]);
}
System.out.println("Total is " + wordCount + " words.");
}
}
Output:
1 This
2 is
3 my
4 sentence
5 and
6 it
7 is
8 not
9 great
Total is 9 words.
A bit more elegant solution using IntStream instead of a for-loop:
import java.util.stream.IntStream;
public class ExampleSolution
{
public static void main(String[] args)
{
String sentence = "This is my sentence and it is not great";
String[] splitted = sentence.split("\\s+");
IntStream.range(0, splitted.length)
.mapToObj(i -> (i + 1) + " " + splitted[i])
.forEach(System.out::println);
System.out.println("Total is " + splitted.length + " words.");
}
}
Try avoiding too much complexity, the following does it just fine
public class MySentenceCounter {
public static void main(String[] args) {
String sentence = "This is my sentence and it is not great";
int ctr = 0;
for (String str : sentence.trim().split("\\s+")) {
System.out.println(++ctr + "" + str) ;
}
System.out.println("Total is " + ctr + " words.");
}
}

Counting even and odd number of letters in words

I am currently trying to count how many words from a textfile have even numbers and odd numbers of characters but I cant seem to get it to work. so far i have done
int countEven = 0;
int countOdd = 0;
for (int i = 0; i <latinLength.length(); i++) {
if (Character.isLetter(latinLength.charAt(i))) {
countEven++;
} else {
countOdd++;
}
}
System.out.println("Total number of unique even words in Latin names = " + countEven);
System.out.println("Total number of unique odd words in Latin names = " + countOdd);
}
i think what i did wrong is i am not accessing the right part of the text file. i do have a get function for the information i want which is getLatinName, but i am not sure how to implement it correctly
String tempLatinName = " ";
String latinLength = " ";
int letters = 0;
for (int i = 0; i < info.size(); i++) {
tempLatinName = info.get(i).getLatinName();
latinLength = tempLatinName.replace(" ","");
letters += latinLength.length();
}
System.out.println("Total number of letters in all Latin names = " + letters);
i have edited the code to show the bit i have done before trying to calculate how many words have odd and even number of characters, the code above is to calculate the total number of characters in each word and then gives me a total
/**
*
* #author g_ama
*/
import java.io.*;
import java.util.*;
public class Task1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
BufferedReader reader = new BufferedReader(new FileReader("shark-data.txt"));
String line;
List<Shark> info = new ArrayList<>();
while ((line = reader.readLine()) != null) {
String[] data = line.split(":");
int MaxLength = Integer.parseInt(data[2]);
int MaxDepth = Integer.parseInt(data[3]);
int MaxYoung;
try {
MaxYoung = Integer.parseInt(data[4]);
} catch (Exception X) {
MaxYoung = -1;
}
int GlobalPresence = Integer.parseInt(data[5]);
ArrayList<String> OceanicRegion = new ArrayList<>();
String[] Region = data[6].split(",");
for (String Element : Region) {
OceanicRegion.add(Element);
}
Shark shark = new Shark(data[0], data[1], MaxLength, MaxDepth, MaxYoung, GlobalPresence, OceanicRegion);
info.add(shark);
}
Collections.sort(info);
System.out.println("The three largest sharks");
System.out.println(info.get(info.size() - 1).getCommonName() + ", " + info.get(info.size() - 1).MaxLength + " cm");
System.out.println(info.get(info.size() - 2).getCommonName() + ", " + info.get(info.size() - 2).MaxLength + " cm");
System.out.println(info.get(info.size() - 3).getCommonName() + ", " + info.get(info.size() - 3).MaxLength + " cm");
System.out.println("The three smallest sharks");
System.out.println(info.get(0).getCommonName() + ", " + info.get(0).MaxLength + " cm");
System.out.println(info.get(1).getCommonName() + ", " + info.get(1).MaxLength + " cm");
System.out.println(info.get(2).getCommonName() + ", " + info.get(2).MaxLength + " cm");
//count total characters for Latin Name
String tempLatinName = " ";
String latinLength = " ";
int letters = 0;
for (int i = 0; i < info.size(); i++) {
tempLatinName = info.get(i).getLatinName();
latinLength = tempLatinName.replace(" ", "");
letters += latinLength.length();
}
System.out.println("Total number of letters in all Latin names = " + letters);
//count even or odd words
int countEven = 0;
int countOdd = 0;
for (int i = 0; i < latinLength.length(); i++) {
if (Character.isLetter(latinLength.charAt(i))) {
countEven++;
} else {
countOdd++;
}
}
System.out.println("Total number of unique even words in Latin names = " + countEven);
System.out.println("Total number of unique odd words in Latin names = " + countOdd);
}
}
Explanation
Currently you are only counting how many letters and non-letters your text has. That is of course not the amount of even words or odd words.
For example if you have a word like
test12foo!$bar
Your code will currently output
countEven => 10 // Amount of letters (testfoobar)
countOdd => 4 // Amount of non-letters (12!$)
Compare this to your if-condition:
if (Character.isLetter(latinLength.charAt(i))) {
countEven++;
} else {
countOdd++;
}
What you want is to count how often the length of your words is even or odd, so suppose words like
test // length 4, even
foo // length 3, odd
bartest // length 7, odd
then you want
countEven => 1 // (test)
countOdd => 2 // (foo, bartest)
Solution
Instead you will need to split your text into words (tokenize). After that you will need to count, for each word, the amount of characters. If that is even you may increase countEven by one. Likewise countOdd++ if it's an odd number.
The core will be this condition
word.length() % 2 == 0
it is true if the word has an even length and false if it's odd. You can easily verify this yourself (% returns the remainder after division, 0 or 1 in this case).
Let's assume your text structure is simple and words are always separated by whitespace, i.e. something like
test foo bar John Doe
All in all your code could then look like
Path path = Paths.get("myFile.txt");
AtomicInteger countEven = new AtomicInteger(0);
AtomicInteger countOdd = new AtomicInteger(0);
Pattern wordPattern = Pattern.compile(" ");
Files.lines(path) // Stream<String> lines
.flatMap(wordPattern::splitAsStream) // Stream<String> words
.mapToInt(String::length) // IntStream length
.forEach(length -> {
if (length % 2 == 0) {
countEven.getAndIncrement();
} else {
countOdd.getAndIncrement();
}
});
System.out.println("Even words: " + countEven.get());
System.out.println("Odd words: " + countOdd.get());
Or without all that Stream stuff:
Path path = Paths.get("myFile.txt");
List<String> lines = Files.readAllLines(path);
List<String> words = new ArrayList<>();
// Read words
for (String line : lines) {
String[] wordsOfLine = line.split(" ");
words.addAll(Arrays.asList(wordsOfLine));
}
// Count even and odd words
int countEven = 0;
int countOdd = 0;
for (String word : words) {
if (word.length() % 2 == 0) {
countEven++;
} else {
countOdd++;
}
}
System.out.println("Even words: " + countEven);
System.out.println("Odd words: " + countOdd);
Adjusted to your specific code
As you've just added your specific code I'll add a solution adapted to it.
In your code the list info contains all Sharks. From those sharks the words you want to consider is represented by Shark#getLatinName. So all you will need to do is some kind of this:
List<String> words = info.stream() // Stream<Shark> sharks
.map(Shark::getLatinName) // Stream<String> names
.collect(Collectors.toList());
and you can use this words exactly as shown in the other code examples. Alternatively you don't need to collect everything into a new list, you can directly stay in the Stream and continue with the stream-approach shown before. All in all:
AtomicInteger countEven = new AtomicInteger(0);
AtomicInteger countOdd = new AtomicInteger(0);
info.stream() // Stream<Shark> sharks
.map(Shark::getLatinName) // Stream<String> names
.mapToInt(String::length) // IntStream length of names
.forEach(length -> {
if (length % 2 == 0) {
countEven.getAndIncrement();
} else {
countOdd.getAndIncrement();
}
});
System.out.println("Even words: " + countEven);
System.out.println("Odd words: " + countOdd);
And substitute this into that part in your code:
//count even or odd words
(substitute here)

Java - Word Frequency

I've created a Java program in Eclipse. The program counts the frequency of each word. For example if the user entered 'I went to the shop' the program would produce the output '1 1 1 2' that is 1 word of length 1 ('I') 1 word of length 2 ('to') 1 word of length 3 ('the') and 2 words of length 4 ('went' , 'shop').
These are the results I'm getting. I don't want the output with a 0 to be shown. How can I hide these and only have the results with 1,2,3,4,5 shown.
The cat sat on the mat
words[1]=0
words[2]=1
words[3]=5
words[4]=0
words[5]=0
import java.util.Scanner;
import java.io.*;
public class mallinson_Liam_8
{
public static void main(String[] args) throws Exception
{
Scanner scan = new Scanner(new File("body.txt"));
while(scan.hasNext())
{
String s;
s = scan.nextLine();
String input = s;
String strippedInput = input.replaceAll("\\W", " ");
System.out.println("" + strippedInput);
String[] strings = strippedInput.split(" ");
int[] counts = new int[6];
int total = 0;
String text = null;
for (String str : strings)
if (str.length() < counts.length)
counts[str.length()] += 1;
for (String s1 : strings)
total += s1.length();
for (int i = 1; i < counts.length; i++){
System.out.println("words["+ i + "]="+counts[i]);
StringBuilder sb = new StringBuilder(i).append(i + " letter words: ");
for (int j = 1; j <= counts[i]; j++) {
}}}}}
I know you asked for Java, but just for comparison, here is how I'd do it in Scala:
val s = "I went to the shop"
val sizes = s.split("\\W+").groupBy(_.length).mapValues(_.size)
// sizes = Map(2 -> 1, 4 -> 2, 1 -> 1, 3 -> 1)
val sortedSizes = sizes.toSeq.sorted.map(_._2)
// sortedSizes = ArrayBuffer(1, 1, 1, 2)
println(sortedSizes.mkString(" "))
// outputs: 1 1 1 2
Simply add a check before you print...
for (int i = 1; i < counts.length; i++) {
if (counts[i] > 0) { //filter out 0-count lengths
System.out.println("words["+ i + "]="+counts[i]);
}
Add an if-statement that checks if the number of words of length 'i' is equal to 0.
If that is true, don't show it, if it is not, show it.
for (int i =0; i < counts.length; i++) {
if (counts[i] != 0) {
System.out.println("words[" + i + "]="+counts[i]);
}
}
Edit:
bbill beat me to it. Our answers both work.
I'd use the Java8 streaming API.
See my example:
// import java.nio.file.*;
import java.util.*;
import java.util.stream.Collectors;
public class CharacterCount {
public static void main(String[] args) {
// define input
String input = "I went to the shop";
// String input = new String(Files.readAllBytes(Paths.get("body.txt")));
// calculate output
String output =
// split input by whitespaces and other non-word-characters
Arrays.stream(input.split("\\W+"))
// group words by length of word
.collect(Collectors.groupingBy(String::length))
// iterate over each group of words
.values().stream()
// count the words for this group
.map(List::size)
// join all values into one, space separated string
.map(Object::toString).collect(Collectors.joining(" "));
// print output to console
System.out.println(output);
}
}
It outputs:
1 1 1 2

Java I want to print the number of characters in a string

I am working on printing the number of characters taken from a users input. So lets say the user enters here is a random test which totals 17 characters. Here is what I have thus far only printing the words in separate lines.
import java.text.*;
import java.io.*;
public class test {
public static void main (String [] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String inputValue;
inputValue = input.readLine();
String[] words = inputValue.split("\\s+");
for (int i = 0; i < words.length; i++) {
System.out.println(words[i]);
}
}
}
str.replaceAll("\\s+","");removes all whitespaces in str and assigns the resultant string to str
str.length() returns number of characters in String str
So when you get the input from user, do this
inputValue=inputValue.replaceAll("\\s+","");
System.out.println(inputValue.length());
Change your for...loop to this:
int total = 0;
for (int i = 0; i < words.length; i++) {
total += words[i].length();
}
System.out.println(total);
Essentially, we're looping through the array of words, getting each word's length, then adding that number of characters to the total counter.
I think we can avoid iteration over words length if we assume, string is separated by blanks only. Here is an example:
public static void main(String args[]) {
String test = "here is a random test";
String[] array = test.split("\\s+");
int size = array.length > 0 ? (test.length() - array.length + 1) : test.length();
System.out.println("Size:" + size);
}
to get the total count you have to assign each words count to a variable. Then print it after for loop.
int count =0;
for (int i = 0; i < words.length; i++) {
count = count + words[i].length();
}
System.out.println(count );
Fewmodification done,
length printed for words and user input.
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String inputValue;
inputValue = input.readLine();
String[] words = inputValue.split("\\s+");
System.out.println("Length of user input = " + inputValue.length());
for (int i = 0 ; i < words.length ; i++) {
System.out.println(words[i]);
System.out.println("Length of word = " + words[i].length());
}
}
Output
here is a random test
Length of user input = 21
here
Length of word = 4
is
Length of word = 2
a
Length of word = 1
random
Length of word = 6
test
Length of word = 4
You can do something like this if you are concerned only with whitespaces:
inputValue = input.readLine();
int len = inputValue.replaceAll(" ", "").length(); //replacing won't effect the original string and will also replace spaces.
System.out.println(len);
System.out.println(inputValue);
so the o/p would be for sample you provided:
17
here is a random test

Categories