# Problem getting number of words in a String

Page 1 of 1

## 3 Replies - 1980 Views - Last Post: 24 July 2010 - 05:32 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=182958&amp;s=7de1337c920a06f22b8a3e2d9f82545e&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 rakesh0

Reputation: -3
• 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

• Professional Lurker

Reputation: 448
• Posts: 1,504
• 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);
}
}

```

### #3 Dogstopper

Reputation: 2965
• Posts: 11,222
• 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.

### #4 macosxnerd101

• Games, Graphs, and Auctions

Reputation: 12127
• Posts: 45,090
• 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: . 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.

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }