Problem getting number of words in a String

to calculate the no of words in a given string

Page 1 of 1

3 Replies - 1324 Views - Last Post: 24 July 2010 - 05:32 AM Rate Topic: -----

#1 rakesh0  Icon User is offline

  • New D.I.C Head

Reputation: -3
  • View blog
  • Posts: 11
  • Joined: 23-July 10

Problem getting number of words in a String

Posted 24 July 2010 - 04:52 AM

hi everyone,,,,i am doing a program to calculate number of words in a string "welcome to java". can anybody give me the solution,,,,,i am unable to find output, my code is as follows,,

class words
{
public static void main (String args[])
{
String name="welcome to java";
t=name.split(' ');
int l=0;
for(int i=0;i<name.length();i++)
{
l++;

}

System.out.println(+l);
}
}

Is This A Good Question/Topic? -1
  • +

Replies To: Problem getting number of words in a String

#2 Nakor  Icon User is offline

  • Professional Lurker
  • member icon

Reputation: 444
  • View blog
  • Posts: 1,492
  • Joined: 28-April 09

Re: Problem getting number of words in a String

Posted 24 July 2010 - 05:14 AM

Ok, a few questions. you've got t=name.split. What exactly is t? You're assigning a value to something that doesn't exist yet. Then you don't even try to use t so what's the point in it. And what are you trying to print out in your System.out?
class words
{
  public static void main (String args[])
  {
    String name="welcome to java";
    t=name.split(' ');
    int l=0;
    for(int i=0;i<name.length();i++)
    {
      l++;
    }

    System.out.println(+l);
  }
}


Was This Post Helpful? 0
  • +
  • -

#3 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2872
  • View blog
  • Posts: 11,031
  • Joined: 15-July 08

Re: Problem getting number of words in a String

Posted 24 July 2010 - 05:25 AM

Nakor was right. String.split(regex) returns an array of Strings that have been split at whatever is specified between the parentheses. Then just get the length of that String. Problem Solved.

String str = "Welcome to Java";
String[] words = str.split(" ")
int numOfWords = words.length;



Also, "java" is a terrible name for a topic in the Java help forum. Try to give your post a meaningful name.
Was This Post Helpful? 0
  • +
  • -

#4 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10566
  • View blog
  • Posts: 39,113
  • Joined: 27-December 08

Re: Problem getting number of words in a String

Posted 24 July 2010 - 05:32 AM

Topic closed. rakesh0, please stop opening duplicate topics.

Also, please use code tags, like so: :code:. If you want to go over how to use code tags, then send me a PM. But please use them, as they really make our members' lives so much easier.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1