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

แชร์
ฝัง
  • เผยแพร่เมื่อ 14 ต.ค. 2024
  • 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/gdsf...
    Cucumber BDD Framework
    ***************************
    ► bit.ly/3F7d69r
    Protractor with Javascript
    ***************************
    ► urlis.net/4udd...
    ####################################
    TH-cam 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

ความคิดเห็น • 99

  • @jashuvadevisetti5860
    @jashuvadevisetti5860 ปีที่แล้ว +7

    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 5 ปีที่แล้ว +32

    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  5 ปีที่แล้ว +1

      Good

    • @rajendramahapatra3293
      @rajendramahapatra3293 3 ปีที่แล้ว +1

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

    • @gautamkumarjha2686
      @gautamkumarjha2686 3 ปีที่แล้ว +2

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

    • @chinna12131
      @chinna12131 3 ปีที่แล้ว +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 2 ปีที่แล้ว

      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 🙏🏽🙏🏽.

  • @harshitranjanrai7837
    @harshitranjanrai7837 2 ปีที่แล้ว +9

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

  • @chinna12131
    @chinna12131 3 ปีที่แล้ว +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 3 ปีที่แล้ว

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

  • @charanbudama2601
    @charanbudama2601 3 ปีที่แล้ว +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);

  • @MartinoxxHD
    @MartinoxxHD 3 ปีที่แล้ว +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 2 ปีที่แล้ว

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

  • @Developer138
    @Developer138 ปีที่แล้ว +2

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

  • @pankajsahu1657
    @pankajsahu1657 ปีที่แล้ว

    String S = "Hidndustan India Ganga";

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

    System.out.println(words.length);

  • @nileshpardeshi7068
    @nileshpardeshi7068 5 ปีที่แล้ว +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 4 ปีที่แล้ว

      have u fount an answer for this?

    • @yasharparis2558
      @yasharparis2558 4 ปีที่แล้ว +3

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

    • @emregeo2799
      @emregeo2799 2 ปีที่แล้ว +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));

    • @komalprabhu1576
      @komalprabhu1576 7 วันที่ผ่านมา

      yes trim will help when we give space

  • @raghusundaram1057
    @raghusundaram1057 2 ปีที่แล้ว +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

  • @saurabhpadwal1427
    @saurabhpadwal1427 2 ปีที่แล้ว +2

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

    • @sdetpavan
      @sdetpavan  2 ปีที่แล้ว

      You are most welcome

  • @EdClarkHYCT
    @EdClarkHYCT 4 ปีที่แล้ว +3

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

  • @shailendraverma4082
    @shailendraverma4082 10 หลายเดือนก่อน +1

    Thank you sir ! Really Helped allot ❤❤

    • @sdetpavan
      @sdetpavan  10 หลายเดือนก่อน

      Welcome

  • @saqlainquazi7600
    @saqlainquazi7600 ปีที่แล้ว

    i

  • @tapaskhandai
    @tapaskhandai 3 ปีที่แล้ว +1

    For loop should be i

    • @shahbajshaikh9196
      @shahbajshaikh9196 3 ปีที่แล้ว +1

      That's what i was thinking...

    • @jagsam123
      @jagsam123 ปีที่แล้ว

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

    • @haribol3383
      @haribol3383 3 หลายเดือนก่อน

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

    • @tapaskhandai
      @tapaskhandai 3 หลายเดือนก่อน

      ​@@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.

  • @dilrubaahmed8302
    @dilrubaahmed8302 2 ปีที่แล้ว +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  2 ปีที่แล้ว +1

      Teckstack9

    • @dilrubaahmed8302
      @dilrubaahmed8302 2 ปีที่แล้ว

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

  • @hefshineatulashokugalmugal7030
    @hefshineatulashokugalmugal7030 ปีที่แล้ว

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

  • @Shreenidhi110
    @Shreenidhi110 10 หลายเดือนก่อน

    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!

  • @shashavalijava9
    @shashavalijava9 4 หลายเดือนก่อน +1

    Thanks ❤❤❤ sir

    • @sdetpavan
      @sdetpavan  4 หลายเดือนก่อน

      Welcome

  • @subhamanand1141
    @subhamanand1141 ปีที่แล้ว

    why the count variable is intialized with 1 not zero?

  • @nainagupta4949
    @nainagupta4949 ปีที่แล้ว

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

    • @adityapanwar9175
      @adityapanwar9175 ปีที่แล้ว

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

  • @prathmeshgabhale8922
    @prathmeshgabhale8922 5 หลายเดือนก่อน

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

  • @Mm-zt1gk
    @Mm-zt1gk 4 ปีที่แล้ว +4

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

    • @Abhishek-Khelge
      @Abhishek-Khelge 4 ปีที่แล้ว

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

  • @prathameshkanthale6796
    @prathameshkanthale6796 3 หลายเดือนก่อน

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

  • @anveshreddy1245
    @anveshreddy1245 3 ปีที่แล้ว

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

  • @anuragbatham5170
    @anuragbatham5170 ปีที่แล้ว

    We can also use String tokeniser.

  • @aadityaballal03
    @aadityaballal03 ปีที่แล้ว

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

    • @amoghchavan970
      @amoghchavan970 ปีที่แล้ว

      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

  • @Hzzzzz6
    @Hzzzzz6 ปีที่แล้ว +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);
    }

  • @remixgimix
    @remixgimix ปีที่แล้ว

    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 ปีที่แล้ว

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

    • @Arjun2mkap3929
      @Arjun2mkap3929 ปีที่แล้ว

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

  • @prasannasp2351
    @prasannasp2351 4 ปีที่แล้ว

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

    • @sasidharnaidu4507
      @sasidharnaidu4507 3 ปีที่แล้ว

      I was thinking so.. not sure of all scenarios

  • @sagarahirrao7599
    @sagarahirrao7599 ปีที่แล้ว

    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?👆

    • @subhojitbiswas3876
      @subhojitbiswas3876 ปีที่แล้ว

      I'll give tomorrow

    • @ScorpioGenesis
      @ScorpioGenesis 11 หลายเดือนก่อน

      @@subhojitbiswas3876 you never came back bro...

  • @Ashkilgaming
    @Ashkilgaming 8 หลายเดือนก่อน

    Why length -1 pls explain simply

  • @bhagya6606
    @bhagya6606 2 ปีที่แล้ว +1

    Nice 👍 explanation

  • @aadil_aahil_sheikhabu5181
    @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

  • @pandutadavarthy8332
    @pandutadavarthy8332 3 ปีที่แล้ว +1

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

  • @sharma3226
    @sharma3226 2 ปีที่แล้ว

    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 🙏🏽🙏🏽.

  • @vaishnavichittimalla3305
    @vaishnavichittimalla3305 3 ปีที่แล้ว

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

  • @joji4776
    @joji4776 3 ปีที่แล้ว +1

    thank you so much

  • @amoghchavan970
    @amoghchavan970 ปีที่แล้ว

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

  • @ramyachaluvadi4922
    @ramyachaluvadi4922 3 ปีที่แล้ว

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

  • @AkashYadav-bo3uq
    @AkashYadav-bo3uq ปีที่แล้ว

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

  • @abinayarajendran99
    @abinayarajendran99 ปีที่แล้ว

    why count is kept as 1 instead of 0?

    • @noorelafifi602
      @noorelafifi602 ปีที่แล้ว

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

  • @saurabhmishra-nn5xs
    @saurabhmishra-nn5xs 2 ปีที่แล้ว

    why count=1 ? sir

  • @Mm-zt1gk
    @Mm-zt1gk 4 ปีที่แล้ว +1

    Nice video

  • @atishmule7310
    @atishmule7310 3 ปีที่แล้ว +1

    What if there is space at end

  • @sagardumane6982
    @sagardumane6982 ปีที่แล้ว

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

  • @swarajsingha616
    @swarajsingha616 2 ปีที่แล้ว

    What if I start blank space before string.

    • @Maghil485
      @Maghil485 4 หลายเดือนก่อน

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

  • @kishorebabu1543
    @kishorebabu1543 4 ปีที่แล้ว

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

    • @puttaviratkumar7316
      @puttaviratkumar7316 4 ปีที่แล้ว

      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)

  • @swayamprakashbhuyan2580
    @swayamprakashbhuyan2580 3 ปีที่แล้ว

    Commenting for better reach

  • @arijitghosh2910
    @arijitghosh2910 ปีที่แล้ว

    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 ☺

  • @lakshmireddy9952
    @lakshmireddy9952 5 ปีที่แล้ว

    well dooooooe

  • @shankarlingam4702
    @shankarlingam4702 2 ปีที่แล้ว

    Wow it's like a 🍰

  • @kvelez
    @kvelez ปีที่แล้ว

    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.");
    }
    }
    }

  • @mrb7931
    @mrb7931 ปีที่แล้ว

    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