Java Program to Count Number of Words in a String - One Line Code

preview_player
Показать описание
Write a Java program to count number of words in a string. In this tutorial, I have explained two approaches to count number of words in a String.

Рекомендации по теме
Комментарии
Автор

bro ur all video is superb great work as always.thnks

TheGuidingLight
Автор

Incase there are leading and trailing spaces we can also try below code
String s=" Hello JAVA world " ;

String s1=s.trim();
int count=s1.split(" ").length;
System.out.println(count);

O/P- 3

successsuccess
Автор

Bro we can loop until str.length()-1..so we can reduce one condition in if condition..
Thank u..

gireeshakumarsollapure
Автор

Hey guys here a simple method to count a no. Of words& space in String

String txt="simple";
int count= txt. Length() ;
S. O. P(count) ;
Very Easy ..Don't mockup the code.... UnderStand & slove
😊

learntolead
Автор

what if your input is multiple sentence and output must be the sentence with the highest number of words? for example. your input is "The quick brown. The quick brown fox. Quick brown." The expected output must be "4", because the second sentence have the highest number of words which is 4.

marckypaoloportas
Автор

Your way of teaching is very good but I'm getting null on some words .Hence writing correct ans below :-

String str="I and learning learning java java java";
Map<String, Integer> map=new HashMap<String, Integer>();
Integer count=1;
String[] arr=str.split(" ");

for(int i=0;i<arr.length;i++) {

if(map.containsKey(arr[i]))
{
map.put(arr[i], count+1);
}
else {
map.put(arr[i], count);
}
}
for(String s:map.keySet()){
System.out.println("The count for "+s+" = "+map.get(s));
}

aryan_mukherjee
Автор

Plz give the code your doing in description it will help everyone

Bhushankadam
Автор

Just subscribed..I would request you to Please speak loud..

shyamprasadatluri
Автор

bro I am new to java, can you please tell me how to write this in java >> if c[i:i+3]
This is from python f you are not familiar with python it means it will check that at index (i to i+3) in variable c which is string.

nabeegh
Автор

What a fucking g. thank you endlessly for this help!!!

CharlesKuter
Автор

what is the use of str.charAt(i+1)!=' '

mohanbabu
Автор

One suggestion sir ... if you will speak in hindi that will make us understand well ...so plzzz !!

Herdripstore
Автор

you are supposed to explain what each of the keywords will do in a program... like "System", "\\s+", what is it's purpose? why are they even there?

vickysanth
welcome to shbcf.ru