In a given string, I want to find the longest word then print it in the console.
The output I get is the second longest word i.e "Today"
, but I should get "Happiest"
instead.
May I know what I am doing wrong? Is there a better/different way to find the longest word in a string?
public class DemoString {
public static void main(String[] args) {
String s = "Today is the happiest day of my life";
String[] word = s.split(" ");
String longword = " ";
for (int i = 0; i < word.length; i++)
for (int j = 1 + i; j < word.length; j++)
if (word[i].length() >= word[j].length())
longword = word[i];
System.out.println(longword + " is the longest word with " + longword.length() + " characters.");
System.out.println(rts.length());
}
}
0009laH
1,90612 silver badges26 bronze badges
asked Apr 6, 2017 at 9:59
Here is a «one-liner» you can use with the Java 8 streams API:
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
String s = "Today is the happiest day of my life";
String longest = Arrays.stream(s.split(" "))
.max(Comparator.comparingInt(String::length))
.orElse(null);
System.out.println(longest);
}
}
Output:
happiest
Try it out here.
answered Apr 6, 2017 at 10:29
Sash SinhaSash Sinha
17.6k3 gold badges22 silver badges40 bronze badges
2
// the below Java Program will find Smallest and Largest Word in a String
class SmallestAndLargestWord
{
static String minWord = "", maxWord = "";
static void minMaxLengthWords(String input)
{
// minWord and maxWord are received by reference
// and not by value
// will be used to store and return output
int len = input.length();
int si = 0, ei = 0;
int min_length = len, min_start_index = 0,
max_length = 0, max_start_index = 0;
// Loop while input string is not empty
while (ei <= len)
{
if (ei < len && input.charAt(ei) != ' ')
{
ei++;
}
else
{
// end of a word
// find curr word length
int curr_length = ei - si;
if (curr_length < min_length)
{
min_length = curr_length;
min_start_index = si;
}
if (curr_length > max_length)
{
max_length = curr_length;
max_start_index = si;
}
ei++;
si = ei;
}
}
// store minimum and maximum length words
minWord = input.substring(min_start_index, min_start_index + min_length);
maxWord = input.substring(max_start_index, max_length);
}
// Driver code
public static void main(String[] args)
{
String a = "GeeksforGeeks A Computer Science portal for Geeks";
minMaxLengthWords(a);
// to take input in string use getline(cin, a);
System.out.print("Minimum length word: "
+ minWord
+ "nMaximum length word: "
+ maxWord);
}
}
**
Input : "GeeksforGeeks A computer Science portal for Geeks"
Output : Minimum length word: A
Maximum length word: GeeksforGeeks
**
answered Apr 22, 2019 at 5:54
instead it should be:
for(int i=0; i < word.length; i++)
{
if(word[i].length() >= rts.length())
{
rts = word[i];
}
}
okandas
11.2k2 gold badges15 silver badges17 bronze badges
answered Apr 6, 2017 at 10:03
tt_emrahtt_emrah
1,0431 gold badge8 silver badges19 bronze badges
String s= "Today is the happiest day of my life by vijayakumar";
String [] word = s.split(" ");
String maxlethWord = "";
for(int i = 0; i < word.length; i++){
if(word[i].length() >= maxlethWord.length()){
maxlethWord = word[i];
}
}
System.out.println(maxlethWord);
answered Jun 4, 2018 at 9:27
I haven’t seen an answer where you create a list of the words.
So here is another way to solve the problem:
String s = "Today is the happiest day of my life";;
List<String> strings = Arrays.asList(s.split(" "));
String biggestWord = Collections.max(strings, Comparator.comparing(String::length));
System.out.println(biggestWord);
Output:
happiest
answered Nov 2, 2020 at 14:07
KrayzzeeKrayzzee
862 silver badges5 bronze badges
You can try like ,
String s="Today is the happiest day of my life";
String[] word=s.split(" ");
String rts=" ";
for(int i=0;i<word.length;i++){
if(word[i].length()>=rts.length()){
rts=word[i];
}
}
System.out.println(rts);
System.out.println(rts.length());
answered Apr 6, 2017 at 10:07
MSDMSD
1,40912 silver badges25 bronze badges
Try this one.
public static void main( String[] args )
{
String s = "Today is the happiest day of my life";
String[] word = s.split( " " );
String rts = " ";
for ( int i = 0; i < word.length; i++ )
{
if ( word[i].length() > rts.length() )
rts = word[i];
}
System.out.println( rts );
}
answered Jun 4, 2018 at 9:40
for(int i=0;i<word.length;i++){
for(int j=0;j<word.length;j++){
if(word[i].length()>=word[j].length()){
if(word[j].length()>=rts.length()) {
rts=word[j];
}
} else if(word[i].length()>=rts.length()){
rts=word[i];
}
}
}
answered Apr 6, 2017 at 10:23
MadhaviMadhavi
4742 gold badges7 silver badges19 bronze badges
Теги: java, length, длина строки, сравнение длины строк
В этой статье мы поговорим про метод length(). Он позволяет определять длину строк в Java и сравнивать длины этих строк между собой. Давайте посмотрим, как это делается.
Описание метода
Вышеупомянутый метод length() возвращает длину строки в Java, при этом длина определяется, как равная числу шестнадцатиразрядных Юникод-символов в исследуемой строке. Метод использует довольно простой синтаксис:
Таким образом, возвращается длина последовательности символов. Но давайте лучше посмотрим, как это происходит на примерах.
Определяем длину строки в Java
Итак, у нас есть строка, в которой надо определить длину:
public class Main { public static void main(String args[]){ String Str1 = new String("Добро пожаловать на сайт Otus.ru!"); String Str2 = new String("Otus.ru" ); System.out.print("Длина строки " Добро пожаловать на сайт Otus.ru!" - " ); System.out.println(Str1.length()); System.out.print("Длина строки " Otus.ru" - " ); System.out.println(Str2.length()); } }Консольный вывод будет следующим:
Длина строки " Добро пожаловать на сайт Otus.ru!" - 33 Длина строки " Otus.ru" – 7Вы можете проверить работу этого метода самостоятельно, используя любой онлайн-компилятор Java, например, этот.
Сравниваем длины строк в Java
Метод length() позволяет не только узнать длину строк, но и сравнить их длины. Вот, как это можно реализовать:
public class Main { public static void main(String args[]) { // Определяем длины строки s1 и s2. String s1 = "В Otus я стану отличным программистом!"; int len1 = s1.length(); String s2 = "В Otus я стану отличным разработчиком!"; int len2 = s2.length(); // Вывод на экран количества символов в каждой строке. System.out.println( "Длина строки "В Otus я стану отличным программистом!": " + len1 + " символов."); System.out.println( "Длина строки "В Otus я стану отличным разработчиком!": " + len2 + " символов."); // Сравнение длин строк s1 и s2. if (len1 > len2){ System.out.println( "nСтрока "В Otus я стану отличным программистом!" длиннее строки "В Otus я стану отличным разработчиком!"."); } if (len1 < len2){ System.out.println( "nСтрока "В Otus я стану отличным программистом!" короче строки "В Otus я стану отличным разработчиком!"."); } else { System.out.println( "nСтроки "В Otus я стану отличным программистом!" и "В Otus я стану отличным разработчиком!" равны."); } } }Получим следующий результат:
Длина строки "В Otus я стану отличным программистом!": 38 символов. Длина строки "В Otus я стану отличным разработчиком!": 38 символов. Строки "В Otus я стану отличным программистом!" и "В Otus я стану отличным разработчиком!" равны.В результате метод length() позволяет нам как узнать длину строки, так и сравнить несколько строк. Но, как вы уже заметили, это был простейший код. Если же вы хотите прокачать навыки Java-разработчика на более продвинутом уровне, добро пожаловать на курс не для новичков:
Java program to calculate length of string – In this article, we will discuss the various methods to calculate the length of a string, str length in Java programming. String length() java has been written in 3 to 4 different ways, you can check out here. If you any queries about source code str length in java, leave a comment here.
The methods used in this article are as follows:
- Using Standard Method
- Using Scanner Class (Predefined method)
- Using Scanner Class
- Using Static Method
- Using Separate Class
A string is a data type used in programming like an integer or a floating point but it is used to represent text whenever it is required instead of numerical.
As you can see, the string mentioned here is “Hello”. The string consists of 5 characters. All of the 5 characters are represented by a pointer. The location is represented by a pointer, in this case, starting from 0 to 4.
Similarly, other strings also have ideal lengths where the space between two words is also counted.
str length in Java – Using Standard Method
To find the length to string, we first taken in a string input in the code itself.
This string input is converted to a character array so as to traverse to the end of string individual character-wise to find the length.
To make this conversion, we can make use of a built in method for strings as below:
char[] len= str.toCharArray(); |
In this character array, we traverse until the end of the array in a loop and keep incrementing the count which is to be stored in a separate integer variable (a).
The end value of this variable (a) is nothing but, the length of our input string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.Scanner; class StringLength { public static void main(String x[]) { Scanner sc=new Scanner(System.in); String str=«Hello World»; char[] len= str.toCharArray(); int a=0; for(char ch : len) { a++; } System.out.println(«Length of a string is :»+a); } } |
Output:
Length of a string is :11 |
Java String Length – Predefined Method
In the above example, we had given inputs manually and predetermined in the code itself and if any changes in value were to be made, the user has to go to the code and make changes.
To avoid this, Scanner class in Java can be made use of.
With the help of Scanner class any primitive type inputs can be read at runtime.
So, for our problem, we will read a string input. String in Java has many predefined methods in it. T
By making use of this predefined method and giving our input string as the String whose length is to be found, we can directly display the length in our output screen.
import java.util.Scanner; class StringLength { public static void main(String x[]) { Scanner sc=new Scanner(System.in); System.out.println(«Enter a string :»); String str=sc.nextLine(); int len=str.length(); System.out.println(«string contains «+len+« characters); } } |
Output:
Enter a string : very good morning string contains 17 characters |
Using Scanner Class
In here, just like the explanation given above to make use of scanner class to read inputs at runtime, the same method can be used to read our input.
After getting the input, instead of using a predefined method, we can make use of the logic discussed in the beginning by converting the string to a character array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.Scanner; class StringLength { public static void main(String x[]) { int c=0; Scanner sc=new Scanner(System.in); System.out.println(«Enter a string :»); String str=sc.nextLine(); char[] a= str.toCharArray(); for(char ch : a) { c++; } System.out.println(«string contains «+c+» characters»); } } |
Output:
Enter a string : hi how are you string contains 14 characters |
Using Static Method
This technique is made use of for better readability. We have split up the code into two methods in the same class.
The main method is responsible for all the input and output operations. Input is taken in with the help of Scanner class.
After taking input, a separate static method (length) consisting of the set of statements for calculation of length of string is called.
This method (length) converts individual alphabet to character and increments the count to finally find the total length of the string.
After executing all the statements in it, returns the length of the string. The main logic is enclosed in a try block so that we can catch if any exception occurs like a null pointer, out of bound, etc.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.util.Scanner; class StringLength { public static void main(String arg[]) { Scanner sc=new Scanner(System.in); System.out.println(«Enter a string :»); String str=sc.nextLine(); int res=length(str); System.out.println(«string contains «+res+» characters»); } static int length(String s) { int j=0; try { for ( j = 0;;j++) s.charAt(j); } catch (Exception e) { } return j; } } |
Output:
Enter a string : welcome to java world string contains 21 characters |
Описание
Метод length() – возвращает длину строки в Java. Длина равна числу 16-разрядных символов Юникода в строке.
Синтаксис
Синтаксис этого метода:
public int length()
Параметры
Подробная информация о параметрах:
- нет.
Возвращаемое значение
- В Java length() возвращает длину последовательности символов, представленного этим объектом.
Ниже представлен пример метода length(), который поможет определить длину строки.
import java.io.*;
public class Test {
public static void main(String args[]){
String Str1 = new String("Добро пожаловать на ProgLang.su");
String Str2 = new String("ProgLang.su" );
System.out.print("Длина строки "Добро пожаловать на ProgLang.su" - " );
System.out.println(Str1.length());
System.out.print("Длина строки "ProgLang.su" - " );
System.out.println(Str2.length());
}
}
Получим следующий результат:
Длина строки "Добро пожаловать на ProgLang.su" - 31
Длина строки "ProgLang.su" - 11
Пример 2: сравнение длины строк
Также с помощью метода length() можно не только узнать длину строки, но и сравнить длину строк. Ниже представлен пример как это можно сделать.
public class Test {
public static void main(String args[]) {
// Определение длины строки s1 и s2.
String s1 = "Я стану отличным программистом!";
int len1 = s1.length();
String s2 = "Я стану отличным разработчиком!";
int len2 = s2.length();
// Вывод на экран количества символов в каждой строке.
System.out.println( "Длина строки "Я стану отличным программистом!": " + len1 + " символ.");
System.out.println( "Длина строки "Я стану отличным разработчиком!": " + len2 + " символ.");
// Сравнение длин строк s1 и s2.
if (len1 > len2){
System.out.println( "nСтрока "Я стану отличным программистом!" длинее строки "Я стану отличным разработчиком!".");
}
if (len1 < len2){
System.out.println( "nСтрока "Я стану отличным программистом!" короче строки "Я стану отличным разработчиком!".");
}
else {
System.out.println( "nСтроки "Я стану отличным программистом!" и "Я стану отличным разработчиком!" равны.");
}
}
}
Получим следующий результат:
Длина строки "Я стану отличным программистом!": 31 символ.
Длина строки "Я стану отличным разработчиком!": 31 символ.
Строки "Я стану отличным программистом!" и "Я стану отличным разработчиком!" равны.
How to find the length of a Java String
Follow these steps to find the length of a String in Java:
- Declare a variable of type String
- Initialize the String variable to a non-null value
- Call the Java String length() method
- Hold the value of the String length in a variable for future use
Java String length method()
The Java String class contains a length() method that returns the total number of characters a given String contains.
This value includes all blanks, spaces, and other special characters. Every character in the String is counted.
String Class JavaDoc (Java 17) public int length() - returns the number of characters in a text string
Java String length() example
Here is a simple example of how to find the length of a String in Java and print the value out to the console:
String javaString = " String length example "; int stringSize= javaString.length(); System.out.println(stringSize); //This Java String length example prints out 25
How do I remove whitespace from a Java String’s length?
In the above example of Java’s String length method, the output for the size of the String is 25. The String length method includes the whitespace padding at the beginning and the end of the String.
Quite often, when validating input or manipulating text, you want to eliminate leading and trailing whitespace. This can be achieved through the use of the Java String’s trim method.
String javaString = " String length example "; int stringSize= javaString.trim().length(); System.out.println(stringSize); //This Java String length trim example prints out 21
As you can see with the example above, the whitespaces are not included in the calculation of the length of a String when the trim method is called first.
String method | Method function |
trim() | removes whitespace before the Java String’s length method is called |
charAt(int index) | Returns the character at a given position in a String |
toUpperCase() | Converts all characters in a String to uppercase |
toLowerCase() | Converts all characters in a String to lowercase |
substring(int index) | Returns a subset of the Java String |
String length method vs property
Be careful not to confuse the String length() method with the length property of an array.
The Java String length() method of an array is followed by round brackets, while the Java String length property is not.
Developers often confuse the Java String length method with the length property of an array.
String length compile errors
If you leave the round brackets off the Java String’s length method, the following compile time error results:
Java String error: length cannot be resolved or is not a field
Also be sure to initialize the Java String before you invoke the length() method, or else a NullPointer runtime exception results.
To find the length of a String, make sure you invoke the length() method, not the length property.
Advanced Java String length example
There are many scenarios where a program must first find the length of a Java String.
Here is a rather advanced piece of code that checks to see if a given String is a palindrome. I used a variety of methods from the String class, including length(), charAt() and substring().
package com.mcnz.servlet;
/* Find the length of a Java String example */
public class JavaPalindromeCheckProgram {
public static void main(String[] args) {
boolean flag = palindromeCheck("amanaplanacanalpanama");
System.out.println(flag);
}
/* This code uses the Java String length method in its logic */
public static boolean palindromeCheck(String string){
/* check if the Java String length is zero or one */
if(string.length() == 0 || string.length() == 1) {
return true;
}
if(string.charAt(0) == string.charAt(string.length()-1)) {
return palindromeCheck(string.substring(1, string.length()-1));
}
return false;
}
}
Using Java’s String length method
To get the number of characters in a given piece of text, the Java String length() method is all you need.
Just make sure the String is not null, and avoid any confusion between Java’s length vs length() constructs, and you will have no problem manipulating text Strings in Java.
Trusted answers to developer questions
Educative Answers Team
Grokking the Behavioral Interview
Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.
The length of a string
is referred to as the total number of characters it contains.
The length() method
To calculate the length of a string in Java, you can use an inbuilt length()
method of the Java string class.
In Java, strings are objects created using the string class and the length()
method is a
public
member method of this class. So, any variable of type string
can access this method using the .
(dot) operator.
The length()
method counts the total number of characters in a String.
Method signature
The signature of the length()
method is as follows:
The return type of the length() method is int
.
Example
Let’s calculate & printout the length of a string
using the length()
method.
class CalcLength {
public static void main( String args[] ) {
String name = "educative"; //Initilizing a String Object name
int length = name.length(); //Calling the inbuilt lenght() method
System.out.println("The length of the String ""+name+"" is: " +length); }
}
The length of the string name
is 9:
1 of 12
1 of 12
1 of 12
1 of 12
1 of 12
Trusted Answers to Developer Questions
Learn in-demand tech skills in half the time
Copyright ©2023 Educative, Inc. All rights reserved.
Did you find this helpful?
Write a program that finds the longest word from a sentence. Your program should read a sentence as input from the user and return the longest word. In case there are two words of maximum length return the word which comes first in the sentence.
Input and Output Format
- Input consists of a string with a maximum size of 100 characters.
- The output consists of a single string.
Refer sample output for formatting specifications
Sample Input 1:
Welcome to the world of Programming
Sample Output 1:
Programming
Sample Input 2:
ABC DEF
Sample Output 2:
ABC
Java program to find the longest word in the sentence using String Tokenizer
Following are the steps to find the longest word in the sentence:
- Input a string.
- Pass the string to the lengthiestString() method.
- Now, inside this method, first, initialize the variable max to 0 and create a new string s2.
- Use the StringTokenizer class to break the string into tokens.
- Now, iterate the string till it has tokens. Move the token into a new string and calculate the length.
- Here, check if the length is greater than the next token and store it in the s2 string, and at last return the longest token.
package testCases; import java.util.Scanner; import java.util.StringTokenizer; public class MainJava { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s1= sc.nextLine(); System.out.println(lengthiestString(s1)); } public static String lengthiestString(String s1) { int max=0; String s2=new String(); StringTokenizer t=new StringTokenizer(s1," "); while(t.hasMoreTokens()){ String s3=t.nextToken(); int n=s3.length(); if(n>max){ max=n; s2=s3;} } return s2; } }
Output
This is another approach to finding longes word. Following are the steps to find the longest word in the sentence:
- Input a sentence.
- Now, split the sentence into words using the split() method and store it into an array of words.
- Now, set a variable longest word length to 0.
- Then, check all the words and compare the length with the longest variable length and print the longest word.
package com.date; import java.util.Scanner; public class LongestWord { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String input_string = scanner.nextLine(); String [] words = input_string.split(" "); String longest_word = ""; int longest_word_len = 0; for(int i= 0; i < words.length;i++){ String word = words[i]; int len = word.length(); if(len > longest_word_len ){ longest_word = word; longest_word_len = len; } } System.out.println(longest_word); } }
Output
Longest word in a sentence using Java 8 version
We can find the longest word using Java 8 features easily. Following are the steps to achieve this:
- First, input string using nextLine() method.
- Now, use the Java 8 feature and find the longest word in one line using the below steps:
- Create an array of streams and pass the sentence to the method and split it based on the space.
- Call the method max to find the maximum which accepts the Comparator interface. Call the comapreInt() method and pass the string length using the method reference.
- And, for the other case pass null.
- At last, just print the longest word.
package com.date; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; public class Main5 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String input_string = scanner.nextLine(); String longest_word = Arrays.stream(input_string.split(" ")).max(Comparator.comparingInt(String::length)).orElse(null); System.out.println(longest_word); } }
Output
Thus, in this way, we learn How to find the longest word in the string in Java.
Today, I am going to share with you Java interview questions from Google, which were asked to one of my readers during the telephonic round. How do you count the number of words in a given String in Java? You can count words in Java String by using the split() method of String. A word is nothing but a non-space character in String, which is separated by one or multiple spaces. By using a regular expression to find spaces and split on them will give you an array of all words in a given String. This was the easy way to solve this problem as shown here, but if you have been asked to write a program to count a number of words in a given String in Java without using any of String utility methods like String.split() or StringTokenizer then it’s a little bit challenging for a beginner programmer.
It’s actually one of the common Java coding questions and I have seen it a couple of times with Java developer interviews of 2 to 4 years of experience, not just with Google but companies like Barclays, Nomura, Citibank, JP Morgan, and Amazon.
The interviewer also put additional constraints like split() is not allowed, you can only use basic methods like charAt(), length(), and substring() along with the loop, operators, and other basic programming tools.
In this article, I’ll share all three ways to solve this problem i.e. first by using String’s split() method and regular expression, second by using StringTokenizer, and third without using any library method like above.
The third one is the most interesting and very difficult to write a complete solution handling all special characters e.g. non-printable ASCII characters. for our purpose, we assume that space character includes tab, space, or newline and anything which is considered as a letter by Character.isLetter() is considered as a word.
Btw, if you are looking for more String based coding problems, you can either check here, or you can check out Data Structures and Algorithms: Deep Dive Using Java course on Udemy. It not only provides is a collection of common programming questions and solutions from tech giants like Amazon, Google, Facebook, and Microsoft but also useful to refresh your Data Structure and algorithm skills.
How to Count Number of Words in Given String in Java?
Without wasting any more of your time, here are my three solutions to this common coding problem. In the first method we will use the split() method of String class, in the second we will use StringTokenizer, and in the third, we’ll solve this problem without using any API or library method.
Solution 1 — Counting words using String.split() method
In this solution, we will use the split() method of java.lang.String class to count the number of words in a given sentence. This solution uses the regular expression «\s+» to split the string on whitespace. The split method returns an array, the length of the array is your number of words in a given String.
public static int countWordsUsingSplit(String input) { if (input == null || input.isEmpty()) { return 0; } String[] words = input.split("\s+"); return words.length; }
If you are new to a regular expression in Java, the s is a character class to detect space including tabs, since needs to be escaped in Java, it becomes \s and because there could be multiple spaces between words we made this regular expression greedy by adding +, hence \s+ will find one more space and split the String accordingly.
You can also see The Complete Java MasterClass course by Tim Buchalaka on Udemy to learn more about the split() method of String class and regular expression in Java. This is also the simplest way to count the number of words in a given sentence.
Solution 2 — Counting word in String using StringTokenizer
Constructs a string tokenizer for the specified string. The tokenizer uses the default delimiter set, which is » tnrf»: the space character, the tab character, the newline character, the carriage-return character, and the form-feed character. Delimiter characters themselves will not be treated as tokens
public static int countWordsUsingStringTokenizer(String sentence) { if (sentence == null || sentence.isEmpty()) { return 0; } StringTokenizer tokens = new StringTokenizer(sentence); return tokens.countTokens(); }
You can see that we have not given any explicit delimiter to StringTokenizer, it uses the default set of delimiters which is enough to find any whitespace and since words are separated by whitespace, the number of tokens is actually equal to the number of words in given String. See Java Fundamentals Part 1 and 2 on Pluralsight for more information on the StringTokenizer class in Java. You need a membership, but even if you don’t have you can use their 10-day free pass to access this course for free.
Solution 3 — Counting word in String without using library method
Here is the code to count a number of words in a given string without using any library or utility method. This is what you may have written in C or C++. It iterates through the String array and checks every character. It assumes that a word starts with a letter and ends with something which is not a letter. Once it encounters a non-letter it increments the counter and starts searching again from the next position.
public static int count(String word) { if (word == null || word.isEmpty()) { return 0; } int wordCount = 0; boolean isWord = false; int endOfLine = word.length() - 1; char[] characters = word.toCharArray(); for (int i = 0; i < characters.length; i++) { // if the char is a letter, word = true. if (Character.isLetter(characters[i]) && i != endOfLine) { isWord = true; // if char isn't a letter and there have been letters before, // counter goes up. } else if (!Character.isLetter(characters[i]) && isWord) { wordCount++; isWord = false; // last word of String; if it doesn't end with a non letter, it // wouldn't count without this. } else if (Character.isLetter(characters[i]) && i == endOfLine) { wordCount++; } } return wordCount; }
This code is complete and we will see the method live in action in the next paragraph where we’ll combine all three solutions in a single Java program and test.
Java Program to count a number of words in String
Here is our complete Java program to count a number of words in a given String sentence. It demonstrates all three examples we have seen so far like using the String.split() method, using StringTokenizer, and writing your own method to count the number of words without using any third-party library e.g. Google Guava or Apache Commons.
import java.util.StringTokenizer; /* * Java Program to count number of words in String. * This program solves the problem in three ways, * by using String.split(), StringTokenizer, and * without any of them by just writing own logic */ public class Main { public static void main(String[] args) { String[] testdata = { "", null, "One", "O", "Java and C++", "a b c", "YouAre,best" }; for (String input : testdata) { System.out.printf( "Number of words in stirng '%s' using split() is : %d %n", input, countWordsUsingSplit(input)); System.out.printf( "Number of words in stirng '%s' using StringTokenizer is : %d %n", input, countWordsUsingStringTokenizer(input)); System.out.printf("Number of words in stirng '%s' is : %d %n", input, count(input)); } } /** * Count number of words in given String using split() and regular expression * * @param input * @return number of words */ public static int countWordsUsingSplit(String input) { if (input == null || input.isEmpty()) { return 0; } String[] words = input.split("\s+"); return words.length; } /** * Count number of words in given String using StirngTokenizer * * @param sentence * @return count of words */ public static int countWordsUsingStringTokenizer(String sentence) { if (sentence == null || sentence.isEmpty()) { return 0; } StringTokenizer tokens = new StringTokenizer(sentence); return tokens.countTokens(); } /** * Count number of words in given String without split() or any other utility * method * * @param word * @return number of words separated by space */ public static int count(String word) { if (word == null || word.isEmpty()) { return 0; } int wordCount = 0; boolean isWord = false; int endOfLine = word.length() - 1; char[] characters = word.toCharArray(); for (int i = 0; i < characters.length; i++) { // if the char is a letter, word = true. if (Character.isLetter(characters[i]) && i != endOfLine) { isWord = true; // if char isn't a letter and there have been letters before, // counter goes up. } else if (!Character.isLetter(characters[i]) && isWord) { wordCount++; isWord = false; // last word of String; if it doesn't end with a non letter, it // wouldn't count without this. } else if (Character.isLetter(characters[i]) && i == endOfLine) { wordCount++; } } return wordCount; } } Output Number of words in string '' using split() is : 0 Number of words in string '' using StringTokenizer is : 0 Number of words in string '' is : 0 Number of words in string 'null' using split() is : 0 Number of words in string 'null' using StringTokenizer is : 0 Number of words in string 'null' is : 0 Number of words in string 'One' using split() is : 1 Number of words in string 'One' using StringTokenizer is : 1 Number of words in string 'One' is : 1 Number of words in string 'O' using split() is : 1 Number of words in string 'O' using StringTokenizer is : 1 Number of words in string 'O' is : 1 Number of words in string 'Java and C++' using split() is : 3 Number of words in string 'Java and C++' using StringTokenizer is : 3 Number of words in string 'Java and C++' is : 3 Number of words in string 'a b c' using split() is : 3 Number of words in string 'a b c' using StringTokenizer is : 3 Number of words in string 'a b c' is : 3 Number of words in string 'YouAre,best' using split() is : 1 Number of words in string 'YouAre,best' using StringTokenizer is : 1 Number of words in string 'YouAre,best' is : 2
You can see that our program is working fine and it can correctly identify a number of words in a given String.
If you want to practice some more of this type of question, you can also check the Cracking the Coding Interview book, one of the biggest collections of Programming Questions, and Solutions from technical interviews. It also includes questions from service-based companies like Infosys, TCS, and Cognizant.
That’s all about how to count a number of words in Java String. I have shown you three ways to solve this problem, first by using the split() method and regular expression, second by using StringTokenizer class, and third without using any library method to solve this problem directly like split or StringTokenizer.
Depending upon your need, you can use any of these methods. The interviewer usually asks you to do it in a third way, so be ready for that. You can also check out the following resources and coding problems to gain more practice and confidence.
Other String based coding problems you may like to solve
- How to reverse a String in place in Java? (solution)
- How to find all permutations of a given String in Java? (solution)
- How to check if a given number is prime or not? (solution)
- 10 Free Courses to learn Data Structure and Algorithms (courses)
- How to find the highest occurring word from a text file in Java? (solution)
- 100+ Data Structure and Algorithms Problems (solved)
- 10 Books to learn Data Structure and Algorithms (books)
- How to check if two given Strings are Anagram in Java? (solution)
- 101 Coding Problems and a few tips for Tech interviews (tips)
- How to check if the given string is palindrome or not in Java? (solution)
- How to remove duplicate characters from String in Java? (solution)
- 10 Data Structure and Algorithms course to crack coding interview (courses)
- How to check if a String contains duplicate characters in Java? (solution)
- How to find the highest occurring word from a given file in Java? (solution)
- How to count vowels and consonants in a given String in Java? (solution)
- 21 String coding Problems from Technical Interviews (questions)
- How to reverse words in a given String in Java? (solution)
Thanks for reading this article so far. If you find this String-based Java coding problem from Google and my explanation useful then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.
P. S. — If you are preparing for a programming job interview, then you must prepare for an all-important topic like data structure, String, array, etc. One course which can help you with this task is the Grokking the Coding Interview: Patterns for Coding Questions course on Educativa. It contains popular coding interview patterns which will help you to solve most of the problems in your coding interviews.
$begingroup$
Is this a smart method?
public static ArrayList<Integer> getWordLengths( String s )
{
String str = " " + s + " ";
ArrayList<Integer> list = new ArrayList<Integer>();
for ( int i = 0; i < str.length(); i++ )
{
if ( str.charAt(i) == ' ' )
{
for ( int j = i+1; j < str.length() ; j++)
{
if ( str.charAt(j) == ' ')
{
list.add( j - i - 1 );
j = str.length();
}
}
}
}
return list;
}
Sample output:
System.out.println( getWordLengths("This is really easy"));
[4, 2, 6, 4]
so it worked.
We are only allowed to use length and charAt
from the String
class.
Jamal
34.8k13 gold badges132 silver badges236 bronze badges
asked Dec 24, 2014 at 3:09
$endgroup$
1
$begingroup$
Code:
String s = "This is really easy";
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
System.out.println("count is " + count);
count = 0;
} else {
count++;
}
}
System.out.println("count is " + count);
Output:
count is 4
count is 2
count is 6
count is 4
Explanation:
keep counting the length of each word till you see a blank. As soon as, you see a blank, write down a length current word and set count to zero and make it ready for new word. At the end, you should write down the length the last word outside of the for loop.
Note: Big o of my code is n , yet your is n^2; therefore, my method is faster than your approach.
answered Dec 24, 2014 at 3:32
Kick ButtowskiKick Buttowski
$endgroup$
1
$begingroup$
//only allowed to use length and charAt from string class
public static ArrayList<Integer> getWordLengths( String s )
{
String str = s + " ";
ArrayList<Integer> list = new ArrayList<Integer>();
int count = 0;
for ( int i = 0; i < str.length(); i++ )
{
if ( str.charAt(i) == ' ' )
{
list.add(count);
count = 0;
}
else
{
count++;
}
}
return list;
}
Output:
[4, 2, 6, 4]
As long as the length and charAt limitations only apply to string methods and not to use of a List this should be fine. Just because you need to count more than one thing doesn’t mean you need more than one loop.
answered Dec 24, 2014 at 3:43
candied_orangecandied_orange
7981 gold badge6 silver badges21 bronze badges
$endgroup$
0
$begingroup$
There is a split method for String
that will split your string into an array of String
s based on the value you give it.
So in this case you could use spaces:
String[] arr = s.split(" ");
int[] result = arr.length;
for(int x = 0; x < arr.length; x++) {
result[x] = arr[x].length();
}
Since you can only use length and charAt
, you could also do it this way, which is faster. list
will contain the lengths of each word. prev
keeps track of the start of the word you’re on, so you can use it to subtract when you find the next space. You have to add 1 to it each time so that it will be on the beginning of the word instead of the space.
ArrayList<Integer> list = new ArrayList<Integer>();
int prev = 0;
for(int x = 0; x <= line.length(); x++) {
if(x == line.length() || line.charAt(x) == ' ') {
list.add(x - prev);
prev = x + 1;
}
}
Check out the String
class API! If you want to look into split more, here are some good examples!
Jamal
34.8k13 gold badges132 silver badges236 bronze badges
answered Dec 24, 2014 at 3:15
haleyhaley
1113 bronze badges
$endgroup$
7
$begingroup$
If you aren’t allowed to use ArrayList, or if you just think tail recursion is cool, you can do it this way:
public static void main(String[] args) {
System.out.println( getWordLengths("This is really easy") );
}
public static String getWordLengths( String s )
{
return "[" + getWordLengthsRecursively(s, 0, 0, 0) + "]";
}
public static String getWordLengthsRecursively( String s, int i, int start, int end )
{
// Last word
if ( s.length() == i)
{
return "" + (end - start);
}
// Found a word
if ( s.charAt(i) == ' ' )
{
return (end - start) + ", " + getWordLengthsRecursively(s, ++i, i, i);
}
// Word not found. Move to next character.
else
{
return getWordLengthsRecursively(s, ++i, start, ++end);
}
}
Output:
[4, 2, 6, 4]
I like it when I don’t have to import anything. Don’t you?
answered Dec 24, 2014 at 4:55
candied_orangecandied_orange
7981 gold badge6 silver badges21 bronze badges
$endgroup$