473,403 Members | 2,284 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,403 software developers and data experts.

count number of words in a string

Hi,
Just a small excerise for me.
A program that counts number of words in a string.

The program which i have written now is -
Expand|Select|Wrap|Line Numbers
  1. import java.io.*;
  2. class countword 
  3. {
  4.     private static BufferedReader stdin = new BufferedReader(new InputStreamReader( System.in ));
  5.  
  6.     public static void main(String arg[]) throws IOException  {
  7.     System.out.println("Enter a string: ");
  8.     String input = stdin.readLine();
  9.  
  10.     String[] arr = input.split(" ");
  11.     int length = arr.length;
  12.     System.out.println ("Lenght of string: "+input+" is:"+length);
  13.    }
  14. }
  15.  
But this counts even extra blank spaces. Like this string "I am new to JAVA",
or " I am new to java" should count only as 5 words, but the result shows more than that.

Any suggestions to change the logic?


Cheers,

Kishore
Jan 12 '07 #1
12 55893
r035198x
13,262 8TB
Hi,
Just a small excerise for me.
A program that counts number of words in a string.

The program which i have written now is -

import java.io.*;
class countword
{
private static BufferedReader stdin = new BufferedReader(new InputStreamReader( System.in ));

public static void main(String arg[]) throws IOException {
System.out.println("Enter a string: ");
String input = stdin.readLine();

String[] arr = input.split(" ");
int length = arr.length;
System.out.println ("Lenght of string: "+input+" is:"+length);
}
}


But this counts even extra blank spaces. Like this string "I am new to JAVA",
or " I am new to java" should count only as 5 words, but the result shows more than that.

Any suggestions to change the logic?


Cheers,

Kishore
From
Expand|Select|Wrap|Line Numbers
  1.  String[] arr = input.split(" ");
then you do
Expand|Select|Wrap|Line Numbers
  1.  int count = 0; 
  2. for(int i = 0; i <arr.length;i++) {
  3. if(arr[i].equals(" ")) {
  4. }
  5. else {
  6.     count++;
  7. }
  8. }
  9.  
and
Expand|Select|Wrap|Line Numbers
  1.  int length = count;
Jan 12 '07 #2
hey,
that was a very quick reply!! Really unexpected and great ;-)

it works fine.

Thanks a lot!

Cheers,
Kishore
Jan 12 '07 #3
r035198x
13,262 8TB
hey,
that was a very quick reply!! Really unexpected and great ;-)

it works fine.

Thanks a lot!

Cheers,
Kishore
Anytime Kishore. Just remember to use code tags next time you post your code either in helping others or in asking more questions
Jan 12 '07 #4
Anytime Kishore. Just remember to use code tags next time you post your code either in helping others or in asking more questions
I am a newbie to this forum, but i get what u meant :-)

hey, is there any other method WITHOUT USING SPLIT() for this program?
Jan 12 '07 #5
r035198x
13,262 8TB
I am a newbie to this forum, but i get what u meant :-)

hey, is there any other method WITHOUT USING SPLIT() for this program?
Combination of split and a regular expression is the best approach. The tokenizer route is becoming archaic
Jan 12 '07 #6
Combination of split and a regular expression is the best approach. The tokenizer route is becoming archaic
No clue how to go about it...HELP!!!
Jan 12 '07 #7
r035198x
13,262 8TB
No clue how to go about it...HELP!!!
You'd need to go through a regular expression tutorial first. One is found here
Jan 12 '07 #8
Looks like the solution is instead to use input.split("\\s+") to get the count instead of input.split(" ") and then just output the length.
Nov 14 '10 #9
"one&two#three|four" will return as 4 words.
"I'm here" 3 words and so on.
Just didn't think " " is enough to separate words.

Expand|Select|Wrap|Line Numbers
  1. public static int countWords(String s) {
  2.     int counter = 0;
  3.     boolean word = false;
  4.     int endOfLine = s.length()-1;
  5.  
  6.     for (int i = 0; i < s.length(); i++) {
  7.       //if the char is letter, word = true.
  8.       if (Character.isLetter(s.charAt(i)) == true && i != endOfLine) {
  9.         word = true;
  10.       //if char isnt letter and there have been letters before (word == true), counter goes up.
  11.       } else if (Character.isLetter(s.charAt(i)) == false && word == true) {
  12.         counter++;
  13.         word = false;
  14.       //last word of String, if it doesnt end with nonLetter it wouldnt count without this.
  15.       } else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
  16.         counter++;
  17.       }
  18.     }
  19.     return counter;
  20.   }
Nov 16 '10 #10
eeree
1
Try splitting with Regular Expressions instead of using " " as delimiter:
Expand|Select|Wrap|Line Numbers
  1. String[] arr = input.split("\\s+");
  2.      int length = arr.length;
That code will split String on any space character (space \n \r or \t) (if there is more characters in a row it will split only once).
Nov 23 '11 #11
Could use the following code:

import java.io.*;

public class Countstringwords {

private static BufferedReader stdin = new BufferedReader(new InputStreamReader( System.in ));

public static void main(String arg[]) throws IOException {
System.out.println("Enter a string: ");
String input = stdin.readLine();
int i,l = 0;
String[] arr = input.split(" ");
int length = arr.length;
for(i=0;i<length;i++){
System.out.println(arr[i]);
if(!"".equals(arr[i])){l++;}

}
System.out.println ("Lenght of string: "+input+" is:"+l);
} }
Jan 10 '12 #12
can u explain that.,please.,i need explanation.,tnx
Feb 23 '12 #13

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: vic | last post by:
Hello, Dean Try this: select distinct c1, c2 into #tmp_1 from t1 select count(*) as cnt from #tmp_1 drop table #tmp_1 With best regards.
0
by: DataFreakFromUtah | last post by:
Hello! No question here, just a procedure for the archive. Search critera: count records imported count data imported count number of rows imported count number of records imported record import...
1
by: tranky | last post by:
hi, only one information,please... how to count number of anonymous online users? I use ASP.NET 2.0 thank u tranky
11
by: Mack | last post by:
Hi all, I want to write a program to count number of bits set in a number. The condition is we should not loop through each bit to find whether its set or not. Thanks in advance, -Mukesh
7
by: supriyanaidu | last post by:
Hi i am new to this forum . i am doing small project in that i want to count the number of words in the given .for example in my give file the content will be in this format Firstname, last...
2
by: mfaisalwarraich | last post by:
Hi Everybody, I am using the following code to get the recordset of an external database. Dim dbPatients As Database Dim rsCountPatients As Recordset ' to count number of...
5
by: jambonjamasb | last post by:
I am wanting to create a report that summarises the number of items within a date range. For example I have a FIELD called System_Change. This is a drop down COMBOBOX that uses words like unix,...
1
by: jlt206 | last post by:
This code <?php include("counter.php")?> on the webpage produces the count number. (function code below) I want to place the current number into a variable $MemberNo or into a FormField to be sent...
6
by: cathrine babe | last post by:
How To Count Number Of Words In A Sentence
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.