Frequently Asked Java Program 27: How To Count Words in a String

Sdílet
Vložit
  • čas přidán 18. 10. 2019
  • Topic : How To Count Words in a String
    #########################
    Udemy Courses:
    #########################
    Manual Testing+Agile with Jira Tool
    ************************************
    ► shorturl.at/xNXZ4
    Selenium with Java+Cucumber
    ********************************
    ► shorturl.at/aIKMW
    Selenium with Python & PyTest
    ********************************
    ► shorturl.at/ELW09
    Selenium with python using Robot framework
    ****************************************
    ► shorturl.at/bcDPZ
    API Testing(Postman, RestAssured & SoapUI)
    *****************************************
    ► shorturl.at/uAWY7
    Web & API Automation using Cypress with Javascript
    ********************************************
    ► rb.gy/4uum2n
    Playwright with Javascript
    **************************
    ► shorturl.at/gALZ1
    Jmeter-Performance Testing
    ************************
    ► rb.gy/ocj7r2
    SDET Essencials(Full Stack QA)
    *************************
    ► rb.gy/hlnf2v
    Appium-Mobile Automation Testing
    ************************************
    ► rb.gy/wmzv64
    Java Collections
    *****************
    ► bit.ly/3S66ezE
    Python Programming
    *********************
    ► urlis.net/gdsfpb0s
    Cucumber BDD Framework
    ***************************
    ► bit.ly/3F7d69r
    Protractor with Javascript
    ***************************
    ► urlis.net/4uddm1qb
    ####################################
    CZcams Playlists:
    ####################################
    Manual Testing & Agile
    ***********************
    ► bit.ly/3ujvaYa
    ► bit.ly/3OYzxQj
    SQL
    *************************
    ► bit.ly/3R6XjeG
    ► bit.ly/3nE0a1s
    ► bit.ly/3IeKuuJ
    linux & Shell Scripting
    **********************
    ► bit.ly/3up1Z6a
    ► bit.ly/3nzvGxx
    Java
    **********************
    ► bit.ly/3R9QfOs
    ► bit.ly/3AoRMKM
    ► bit.ly/3IbTTDn
    ► bit.ly/3ybXInv
    ► bit.ly/3yCoHdw
    Selenium With Java+Cucumber
    ********************************
    ► bit.ly/3P2FMm4
    ► bit.ly/3yhiIt4
    ► bit.ly/3uokzet
    ► bit.ly/3a7XIND
    ► bit.ly/3umN2S9
    ► bit.ly/3aar7GW
    ► bit.ly/3y9kD2S
    ► bit.ly/3uhLskn
    Python
    ********************************
    ► bit.ly/3agNgU0
    ► bit.ly/3NJNnoy
    ► bit.ly/2CTQ4mR
    ► bit.ly/3OIYWh1
    Selenium With Python,Pytest&Behave
    ***************************************
    ► bit.ly/3OHHoC9
    ► bit.ly/3IeNLdv
    ► bit.ly/2J4tPeT
    ► bit.ly/3ydSkAq
    Selenium With Python Using Robert Framework
    (Web&API Testing)
    *************************************************
    ► bit.ly/3nUvlpr
    ► bit.ly/3nUvE3z
    API Testing (Postman,SoapUi,&Rest Assured)
    **********************************************
    ► bit.ly/3OXacWY
    ► bit.ly/3yh0UhE
    ► bit.ly/3nC9DWQ
    ► bit.ly/3yGfhNS
    ► bit.ly/3OJa11H
    ► bit.ly/3P2slCC
    Mobile App Testing Appium
    ****************************
    ► bit.ly/3Al49HG
    Performance Testing Jmeter
    *******************************
    ► bit.ly/3nz4fE7
    Maven,Jenkins,Git,Github,CI/CD
    *******************************
    ► bit.ly/3P16HPj
    ► bit.ly/3yhlUVA
    ► bit.ly/3afYfwT
    ► bit.ly/3yGzweG
    ► bit.ly/3yF73Ws
    ► bit.ly/3NCOmH7
    SQL,DB Testing&ETL,Bigdata
    *******************************
    ► bit.ly/3NKOcNY
    ► bit.ly/3OVpDyI
    ► bit.ly/3NEvUy0
    ► bit.ly/3IryxlT
    ► bit.ly/3RkWBLh
    JavaScript Based Automation Tools
    ********************************
    ► bit.ly/3nUx51X
    ► bit.ly/3AqI6Q0
    ► bit.ly/3yeurbT
    ► bit.ly/3ujzpTK
    Selector Hub Tools
    ********************
    ►rb.gy/h3h424
    GraphQL
    ******************
    ► rb.gy/sj3gys
    Cypress API Testing
    ********************
    ► shorturl.at/fjKPX
    Cypress Web Testing
    **********************
    ► shorturl.at/agjlK
    Playwright with Javascipt
    **************************
    ► shorturl.at/adSTY
    #PythonWordCount
    #StringWordCount
    #WordCountProgram
    #PythonStringOps
    #CodingInPython
    #StringManipulation
    #PythonProgramming
    #TextProcessing
    #StringFunctions
    #PythonBeginners
    #CodingTips
    #PythonCoding
    #PythonTricks
    #ProgrammingLogic
    #PythonSnippets
    #TechHelp
    #CodeExamples
    #CodingCommunity
    #PythonDev
    #PythonSolutions
    #ProgrammingInPython
    #LearnToCode
    #CodeNewbie
    #CodeItOut
    #CodingMadeEasy
    #StringParsing
    #AlgorithmPractice
    #CodeLearning
    #PythonAlgorithms
    #StringOperations
    #PythonStrings
    #CodeMastery
    #ProgrammingHelp
    #CodeAcademy
    #PythonTips
    #WordCountChallenge
    #StringHandling
    #CodingJourney
    #CodeSnippets
    #PythonProblems
    #ProblemSolving
    #CodingSolutions
    #PythonExplained
    #StringAnalysis
    #CodeDebugging
    #PythonCommunity
    #ProgrammingQueries
    #PythonParsing
    #CodeGuidance
    #LearnPython

Komentáře • 98

  • @EdClarkHYCT
    @EdClarkHYCT Před 4 lety +3

    Awesome solution 👏🏾👌🏾👍🏽!!! Thanks for this!!!!

  • @jashuvadevisetti5860
    @jashuvadevisetti5860 Před rokem +4

    Easiest way to solve :
    class Test{
    public static void main(String [] args) {
    String str = "hello walcome to java programming";
    String []tokens=str.split(" ");
    System.out.println(tokens.length);
    } }

  • @rajendramahapatra3293
    @rajendramahapatra3293 Před 4 lety +31

    There is one more easy approach.
    String str = “Welcome to the Java tutorials”;
    String strArray[]=str.split(“ “);
    System.out.println(“The number of words in a string is “ + strArray.length);

    • @sdetpavan
      @sdetpavan  Před 4 lety +1

      Good

    • @rajendramahapatra3293
      @rajendramahapatra3293 Před 3 lety +1

      @ it will work. Array declaration and initialisation have been done in one line.

    • @gautamkumarjha2686
      @gautamkumarjha2686 Před 3 lety +2

      This will not give a proper result if there is more than one space.

    • @chinna12131
      @chinna12131 Před 3 lety +5

      @@gautamkumarjha2686 String sentence = "Java easy peasy when we practise and explore";
      String[] words = sentence.split("\\W+");
      System.out.println(words.length);
      The above regex will work.

    • @sharma3226
      @sharma3226 Před 2 lety

      Sir could you Pleasee guide me how to sort number of frequent words used in pdf document. because i want to learn the most important major words for exam would be very helpful 🙏🏽🙏🏽.

  • @anveshreddy1245
    @anveshreddy1245 Před 3 lety

    If I want to count unique words in a string then what should be done

  • @harshitranjanrai7837
    @harshitranjanrai7837 Před 2 lety +6

    public static void main(String[] args) {
    int count=1;
    Scanner sc=new Scanner(System.in);
    String s=sc.nextLine();
    for(int i=0;i

  • @Shreenidhi110
    @Shreenidhi110 Před 7 měsíci

    I have one doubt,If we have space in starting of the sentence,we need to keep cunt as 0,but t wont work for count 1.Please suggest!

  • @saurabhpadwal1427
    @saurabhpadwal1427 Před 2 lety +2

    It's very easy solution...
    Thanks brother...

  • @vaishnavichittimalla3305

    How to get words not number of words ?
    After getting words indicate their index values

  • @shailendraverma4082
    @shailendraverma4082 Před 7 měsíci +1

    Thank you sir ! Really Helped allot ❤❤

  • @nileshpardeshi7068
    @nileshpardeshi7068 Před 4 lety +4

    Hello Pavan sir,
    This program fails if we haven't entered any string as input, the count is showing 1, bcoz by default count is 1. Another thing if the user entered multiple spaces as input then what logic needs to add to find the total count?

    • @Abhishek-Khelge
      @Abhishek-Khelge Před 4 lety

      have u fount an answer for this?

    • @yasharparis2558
      @yasharparis2558 Před 4 lety +3

      Answer:
      String st = "java programming java opps";
      String a[] = st.split("\\W+");
      for(int i=0; i

    • @emregeo2799
      @emregeo2799 Před rokem +1

      I think this can be an answer .
      int count=0;
      for (int i = 0; i < s.trim().length(); i++) {
      if (s.trim().charAt(i)==' '&& s.trim().charAt(i+1)!=' ')
      count++;
      }
      System.out.println((count != 0 ? (count + 1) : 0));

  • @subhamanand1141
    @subhamanand1141 Před 10 měsíci

    why the count variable is intialized with 1 not zero?

  • @aadil_aahil_sheikhabu5181

    how can we put count =1; eg user doesn't want to put any word then still it will show 1 words which is not possible

  • @sharma3226
    @sharma3226 Před 2 lety

    Sir could you Pleasee guide me how to sort number of frequent words used in pdf document. because i want to learn the most important major words for exam would be very helpful 🙏🏽🙏🏽.

  • @hefshineatulashokugalmugal7030

    there are one test case fail in your code ex." atue auah iaajja " output require=3 but your code output is 4

  • @pandutadavarthy8332
    @pandutadavarthy8332 Před 2 lety +1

    Can any one find 2 letter words 3 letter words upto n letter words in given string using java

  • @prasannasp2351
    @prasannasp2351 Před 4 lety

    Can we use string.replaceAll(); and count the sentence without spaces and then difference the original length

  • @prathameshkanthale6796

    Can it work....
    Int a = s .replaceAll(" ", " ").length();
    S.O.Pln("a");

  • @anuragbatham5170
    @anuragbatham5170 Před rokem

    We can also use String tokeniser.

  • @remixgimix
    @remixgimix Před rokem

    The program fails if you give an empty string like this " "and also if you start the string with a space. How do you handle this scenario? Cuz count is initialized to 1.

    • @MrDawg69
      @MrDawg69 Před rokem

      For the second issue...We can add a trim() function.

    • @Arjun2mkap3929
      @Arjun2mkap3929 Před rokem

      If(i==0 &&charAt(I)! =' ') ||(str.charAt(i) ==' ' && str. charAt(i+1) ! =' '))
      Use this condition u will get solution to your problem

  • @Developer138
    @Developer138 Před rokem +2

    int count = s.replaceAll(" ", "").length();
    System.out.println(count);
    i think this looks pretty easy
    love you Sir for ur dedication to videos

  • @nainagupta4949
    @nainagupta4949 Před rokem

    one confusion : in if you used compare "==" for first condition and for 2nd "=" only assignment could you please explain

    • @adityapanwar9175
      @adityapanwar9175 Před rokem

      It's not a single"=" operator there. It's actually "!=" which means not equal to. hope this helps

  • @joji4776
    @joji4776 Před 3 lety +1

    thank you so much

  • @aadityaballal03
    @aadityaballal03 Před rokem

    if more than one spaces occurs consequetively in between string like = "Welcome to java world" , then how to count words?

    • @amoghchavan970
      @amoghchavan970 Před rokem

      String str ="Welcome to java world"; just remove the space of string by str.replaceAll (\\s," ") ; method and then it will be like this Welcometojavaworld then use length method to get the count simple

  • @saqlainquazi7600
    @saqlainquazi7600 Před rokem

    i

  • @sagardumane6982
    @sagardumane6982 Před rokem

    invalid charecter constant showing in first conditions ==' ' ,how to solve this sir anybody knows this

  • @charanbudama2601
    @charanbudama2601 Před 3 lety +8

    can we use this ?
    String s1 ="This is a java program to find the words in the string";
    String [] s2 =s1.split(" ");
    System.out.println("Number of words are " +s2.length);

  • @AkashYadav-bo3uq
    @AkashYadav-bo3uq Před rokem

    Can somebody explain me how to count the number of "and" and "an" in a sentence with working

  • @Ashkilgaming
    @Ashkilgaming Před 5 měsíci

    Why length -1 pls explain simply

  • @bhagya6606
    @bhagya6606 Před 2 lety +1

    Nice 👍 explanation

  • @Mm-zt1gk
    @Mm-zt1gk Před 4 lety +4

    What if string is like "naman-singh"
    It will count them single word i think

    • @Abhishek-Khelge
      @Abhishek-Khelge Před 4 lety

      there are many test cases where it will fail not only this one.

  • @dilrubaahmed8302
    @dilrubaahmed8302 Před 2 lety +1

    some days earleir, Mr. Pavan had shared a link for a new youtuber for learning java and other stuffs.Do anyone know what is the name of the channel?

    • @sdetpavan
      @sdetpavan  Před 2 lety +1

      Teckstack9

    • @dilrubaahmed8302
      @dilrubaahmed8302 Před 2 lety

      @@sdetpavan thanks , but i cannot access in search button..can u share any video link plz?tia

  • @raghusundaram1057
    @raghusundaram1057 Před 2 lety +5

    import java.util.Scanner;
    public class CountwordsinaString {
    public static void main (String args []) {
    Scanner in = new Scanner(System.in);
    System.out.println(" Enter a String");
    String str=in.nextLine();


    int count=1;
    for(int i=0; i

  • @saurabhmishra-nn5xs
    @saurabhmishra-nn5xs Před 2 lety

    why count=1 ? sir

  • @ramyachaluvadi4922
    @ramyachaluvadi4922 Před 3 lety

    Why should give two spaces s.charat (I)== ' '

  • @swarajsingha616
    @swarajsingha616 Před rokem

    What if I start blank space before string.

    • @Maghil485
      @Maghil485 Před měsícem

      Then you need to give int count= 0 instead of 1.

  • @shashavalijava9
    @shashavalijava9 Před měsícem +1

    Thanks ❤❤❤ sir

  • @Mm-zt1gk
    @Mm-zt1gk Před 4 lety +1

    Nice video

  • @chinna12131
    @chinna12131 Před 3 lety +8

    One more easy approach. String sentence = "Java easy peasy when we practise and explore";
    String[] words = sentence.split("\\W+");
    System.out.println(words.length);

    • @bighitlabels2474
      @bighitlabels2474 Před 2 lety

      In this case do we need to add loops also as above program

  • @swayamprakashbhuyan2580

    Commenting for better reach

  • @atishmule7310
    @atishmule7310 Před 3 lety +1

    What if there is space at end

  • @abinayarajendran99
    @abinayarajendran99 Před rokem

    why count is kept as 1 instead of 0?

    • @noorelafifi602
      @noorelafifi602 Před rokem

      @Isha yadav vii b Ad no. 4679 if i make .length() not -1 and count is 0, its correct?

  • @tapaskhandai
    @tapaskhandai Před 2 lety +1

    For loop should be i

    • @shahbajshaikh9196
      @shahbajshaikh9196 Před 2 lety +1

      That's what i was thinking...

    • @jagsam123
      @jagsam123 Před rokem

      Here int is starting from 1....so s.length has taken

    • @haribol3383
      @haribol3383 Před 13 dny

      why its isn't mattering bro? if I am trying so it is giving error

    • @tapaskhandai
      @tapaskhandai Před 13 dny

      ​@@haribol3383because it will not go the last letter of the string. It will find the space character always 2 or 3 characters before the last character. And the goal will be achieved.

  • @pankajsahu1657
    @pankajsahu1657 Před rokem

    String S = "Hidndustan India Ganga";

    String [] words = S.split(" ");

    System.out.println(words.length);

  • @sagarahirrao7599
    @sagarahirrao7599 Před rokem

    List companies = Arrays.asList("HCL","HCL","HCL","HCL","TCS","TCS","TCS","ZINNIA");
    Write a program that returns the name of the company that has the maximum occurennce. for e.g. above list should print HCL
    can i get ans. of this?👆

  • @DomaninNicola
    @DomaninNicola Před 3 lety

    if the string starts with a space it counts it as a word- how can you avoid that?

  • @amoghchavan970
    @amoghchavan970 Před rokem

    ONE MORE EASY APPRORACH JUST REMOVE THE SPACE BY REPLACE ALL METHOD AND THEN COUNT THE LENGTH OF STRING SIMPLE

  • @MartinoxxHD
    @MartinoxxHD Před 3 lety +4

    You can actually use the Scanner class for counting letters:
    private static int cntWords(String phrase) {
    Scanner in = new Scanner(phrase);
    int cnt = 0;
    while (in.hasNext()) {
    cnt++;
    in.next();
    }
    in.close();
    return cnt;
    }

    • @rohithrhegde6597
      @rohithrhegde6597 Před 2 lety

      @edbubble17 , you are awesome!!! never thought can do this using scanner class

  • @kishorebabu1543
    @kishorebabu1543 Před 3 lety

    Why did you take count is 1 what will happen if we take 0 ? please answer my question... thank you

    • @puttaviratkumar7316
      @puttaviratkumar7316 Před 3 lety

      if we are taking count as zero(0) then it should return the number of words must be one less. because it should not count the first word.( we didn't consider the space before the first word)

  • @lakshmireddy9952
    @lakshmireddy9952 Před 4 lety

    well dooooooe

  • @shankarlingam4702
    @shankarlingam4702 Před 2 lety

    Wow it's like a 🍰

  • @Hzzzzz6
    @Hzzzzz6 Před 10 měsíci +1

    public static void main(String[] args) {
    String input = "today is a beautiful day";
    String words[] = input.split(" ");
    int count = 0;
    for (String w : words) {
    count++;
    }
    System.out.println(count);
    }

  • @mrb7931
    @mrb7931 Před rokem

    import java.util.Scanner;
    public class CountTheWords2 {
    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a String");
    String str = sc.nextLine();
    int count = 1;
    for(int i=0;i

  • @prathmeshgabhale8922
    @prathmeshgabhale8922 Před 2 měsíci

    Scanner sc=new Scanner(System.in);
    System.out. println("enter string");
    String s=sc.nextLine();
    String a[ ] = s. split(" ");
    System.out. Println(a. Length);

  • @arijitghosh2910
    @arijitghosh2910 Před rokem

    import java.util.*;;
    public class Count_Word
    {
    public static void main(String[] args)
    {
    Scanner sc = new Scanner(System.in);
    String s = sc.nextLine();
    String[] arr = s.split(" ");
    int count=0;
    System.out.println(Arrays.toString(arr));
    for (int i = 0; i < arr.length; i++) {
    if(arr[i]!="")
    {
    count++;
    }
    }
    System.out.println("Number of word : "+count);
    }
    }
    You can also try it ☺

  • @kvelez
    @kvelez Před 10 měsíci

    import java.util.HashMap;
    import java.util.Scanner;
    public class Main {
    public static void main(String[] args) {
    System.out.print("
    Enter a statement: ");
    Scanner scan = new Scanner(System.in);
    String statement = scan.nextLine();
    scan.close();
    String[] words = statement.split("\\s+");
    HashMap wordHashMap = new HashMap();
    HashMap letterHashMap = new HashMap();
    for (int i = 0; i < statement.length(); i++){
    char currentChar = statement.charAt(i);
    if (letterHashMap.containsKey(currentChar)){
    letterHashMap.put(currentChar, letterHashMap.get(currentChar) + 1);
    } else {
    letterHashMap.put(currentChar, 1);
    }
    }

    for (Character letter : letterHashMap.keySet()){
    int count = letterHashMap.get(letter);
    System.out.println("Letter: " + letter + " appears " + count + " times.");
    }
    for (String word : words){

    if (wordHashMap.containsKey(word)){
    wordHashMap.put(word, wordHashMap.get(word) + 1);
    } else {
    wordHashMap.put(word, 1);
    }

    }

    for (String item : wordHashMap.keySet()){
    int count = wordHashMap.get(item);
    System.out.println("Word: " + item + " appears: " + count + " times.");
    }
    }
    }