Java word count program - java

I am trying to make a program on word count which I have partially made and it is giving the correct result but the moment I enter space or more than one space in the string, the result of word count show wrong results because I am counting words on the basis of spaces used. I need help if there is a solution in a way that no matter how many spaces are I still get the correct result. I am mentioning the code below.
public class CountWords
{
public static void main (String[] args)
{
System.out.println("Simple Java Word Count Program");
String str1 = "Today is Holdiay Day";
int wordCount = 1;
for (int i = 0; i < str1.length(); i++)
{
if (str1.charAt(i) == ' ')
{
wordCount++;
}
}
System.out.println("Word count is = " + wordCount);
}
}

public static void main (String[] args) {
System.out.println("Simple Java Word Count Program");
String str1 = "Today is Holdiay Day";
String[] wordArray = str1.trim().split("\\s+");
int wordCount = wordArray.length;
System.out.println("Word count is = " + wordCount);
}
The ideas is to split the string into words on any whitespace character occurring any number of times.
The split function of the String class returns an array containing the words as its elements.
Printing the length of the array would yield the number of words in the string.

Two routes for this. One way would be to use regular expressions. You can find out more about regular expressions here. A good regular expression for this would be something like "\w+" Then count the number of matches.
If you don't want to go that route, you could have a boolean flag that remembers if the last character you've seen is a space. If it is, don't count it. So the center of the loop looks like this:
boolean prevCharWasSpace=true;
for (int i = 0; i < str1.length(); i++)
{
if (str1.charAt(i) == ' ') {
prevCharWasSpace=true;
}
else{
if(prevCharWasSpace) wordChar++;
prevCharWasSpace = false;
}
}
Update
Using the split technique is exactly equivalent to what's happening here, but it doesn't really explain why it works. If we go back to our CS theory, we want to construct a Finite State Automa (FSA) that counts words. That FSA may appear as:
If you look at the code, it implements this FSA exactly. The prevCharWasSpace keeps track of which state we're in, and the str1.charAt('i') is decideds which edge (or arrow) is being followed. If you use the split method, a regular expression equivalent of this FSA is constructed internally, and is used to split the string into an array.

Java does have StringTokenizer API and can be used for this purpose as below.
String test = "This is a test app";
int countOfTokens = new StringTokenizer(test).countTokens();
System.out.println(countOfTokens);
OR
in a single line as below
System.out.println(new StringTokenizer("This is a test app").countTokens());
StringTokenizer supports multiple spaces in the input string, counting only the words trimming unnecessary spaces.
System.out.println(new StringTokenizer("This is a test app").countTokens());
Above line also prints 5

You can use String.split (read more here) instead of charAt, you will get good results.
If you want to use charAt for some reason then try trimming the string before you count the words that way you won't have the extra space and an extra word

My implementation, not using StringTokenizer:
Map<String, Long> getWordCounts(List<String> sentences, int maxLength) {
Map<String, Long> commonWordsInEventDescriptions = sentences
.parallelStream()
.map(sentence -> sentence.replace(".", ""))
.map(string -> string.split(" "))
.flatMap(Arrays::stream)
.map(s -> s.toLowerCase())
.filter(word -> word.length() >= 2 && word.length() <= maxLength)
.collect(groupingBy(Function.identity(), counting()));
}
Then, you could call it like this, as an example:
getWordCounts(list, 9).entrySet().stream()
.filter(pair -> pair.getValue() <= 3 && pair.getValue() >= 1)
.findFirst()
.orElseThrow(() ->
new RuntimeException("No matching word found.")).getKey();
Perhaps flipping the method to return Map<Long, String> might be better.

Use split(regex) method. The result is an array of strings that was splited by regex.
String s = "Today is Holdiay Day";
System.out.println("Word count is = " + s.split(" ").length);

You need to read the file line by line and reduce the multiple occurences of the whitespaces appearing in your line to a single occurence and then count for the words. Following is a sample:
public static void main(String... args) throws IOException {
FileInputStream fstream = new FileInputStream("c:\\test.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int wordcount = 0;
while ((strLine = br.readLine()) != null) {
strLine = strLine.replaceAll("[\t\b]", "");
strLine = strLine.replaceAll(" {2,}", " ");
if (!strLine.isEmpty()){
wordcount = wordcount + strLine.split(" ").length;
}
}
System.out.println(wordcount);
in.close();
}

public class wordCOunt
{
public static void main(String ar[])
{
System.out.println("Simple Java Word Count Program");
String str1 = "Today is Holdiay Day";
int wordCount = 1;
for (int i = 0; i < str1.length(); i++)
{
if (str1.charAt(i) == ' '&& str1.charAt(i+1)!=' ')
{
wordCount++;
}
}
System.out.println("Word count is = " +(str1.length()- wordCount));
}
}

public class wordCount
{
public static void main(String ar[]) throws Exception
{
System.out.println("Simple Java Word Count Program");
int wordCount = 1,count=1;
BufferedReader br = new BufferedReader(new FileReader("C:/file.txt"));
String str2 = "", str1 = "";
while ((str1 = br.readLine()) != null) {
str2 += str1;
}
for (int i = 0; i < str2.length(); i++)
{
if (str2.charAt(i) == ' ' && str2.charAt(i+1)!=' ')
{
wordCount++;
}
}
System.out.println("Word count is = " +(wordCount));
}
}

you should make your code more generic by considering other word separators as well.. such as "," ";" etc.
public class WordCounter{
public int count(String input){
int count =0;
boolean incrementCounter = false;
for (int i=0; i<input.length(); i++){
if (isValidWordCharacter(input.charAt(i))){
incrementCounter = true;
}else if (incrementCounter){
count++;
incrementCounter = false;
}
}
if (incrementCounter) count ++;//if string ends with a valid word
return count;
}
private boolean isValidWordCharacter(char c){
//any logic that will help you identify a valid character in a word
// you could also have a method which identifies word separators instead of this
return (c >= 'A' && c<='Z') || (c >= 'a' && c<='z');
}
}

import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multiset;
String str="Simple Java Word Count count Count Program";
Iterable<String> words = Splitter.on(" ").trimResults().split(str);
//google word counter
Multiset<String> wordsMultiset = HashMultiset.create();
for (String string : words) {
wordsMultiset.add(string.toLowerCase());
}
Set<String> result = wordsMultiset.elementSet();
for (String string : result) {
System.out.println(string+" X "+wordsMultiset.count(string));
}

public static int CountWords(String str){
if(str.length() == 0)
return 0;
int count =0;
for(int i=0;i< str.length();i++){
if(str(i) == ' ')
continue;
if(i > 0 && str.charAt(i-1) == ' '){
count++;
}
else if(i==0 && str.charAt(i) != ' '){
count++;
}
}
return count;
}

public class CountWords
{
public static void main (String[] args)
{
System.out.println("Simple Java Word Count Program");
String str1 = "Today is Holdiay Day";
int wordCount = 1;
for (int i = 0; i < str1.length(); i++)
{
if (str1.charAt(i) == ' ' && str1.charAt(i+1)!=' ')
{
wordCount++;
}
}
System.out.println("Word count is = " + wordCount));
}
}
This gives the correct result because if space comes twice or more then it can't increase wordcount. Enjoy.

try this
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class wordcount {
public static void main(String[] args) {
String s = "India is my country. I love India";
List<String> qw = new ArrayList<String>();
Map<String, Integer> mmm = new HashMap<String, Integer>();
for (String sp : s.split(" ")) {
qw.add(sp);
}
for (String num : qw) {
mmm.put(num, Collections.frequency(qw, num));
}
System.out.println(mmm);
}
}

To count total words Or to count total words without repeat word count
public static void main(String[] args) {
// TODO Auto-generated method stub
String test = "I am trying to make make make";
Pattern p = Pattern.compile("\\w+");
Matcher m = p.matcher(test);
HashSet<String> hs = new HashSet<>();
int i=0;
while (m.find()) {
i++;
hs.add(m.group());
}
System.out.println("Total words Count==" + i);
System.out.println("Count without Repetation ==" + hs.size());
}
}
Output :
Total words Count==7
Count without Repeatation ==5

Not sure if there is a drawback, but this worked for me...
Scanner input = new Scanner(System.in);
String userInput = input.nextLine();
String trimmed = userInput.trim();
int count = 1;
for (int i = 0; i < trimmed.length(); i++) {
if ((trimmed.charAt(i) == ' ') && (trimmed.charAt(i-1) != ' ')) {
count++;
}
}

You can use this code.It may help you:
public static void main (String[] args)
{
System.out.println("Simple Java Word Count Program");
String str1 = "Today is Holdiay Day";
int count=0;
String[] wCount=str1.split(" ");
for(int i=0;i<wCount.length;i++){
if(!wCount[i].isEmpty())
{
count++;
}
}
System.out.println(count);
}

String data = "This world is mine";
System.out.print(data.split("\\s+").length);

This could be as simple as using split and count variable.
public class SplitString {
public static void main(String[] args) {
int count=0;
String s1="Hi i love to code";
for(String s:s1.split(" "))
{
count++;
}
System.out.println(count);
}
}

public class TotalWordsInSentence {
public static void main(String[] args) {
String str = "This is sample sentence";
int NoOfWOrds = 1;
for (int i = 0; i<str.length();i++){
if ((str.charAt(i) == ' ') && (i!=0) && (str.charAt(i-1) != ' ')){
NoOfWOrds++;
}
}
System.out.println("Number of Words in Sentence: " + NoOfWOrds);
}
}
In this code, There wont be any problem regarding white-space in it.
just the simple for loop. Hope this helps...

To count specified words only like John, John99, John_John and John's only. Change regex according to yourself and count the specified words only.
public static int wordCount(String content) {
int count = 0;
String regex = "([a-zA-Z_’][0-9]*)+[\\s]*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(content);
while(matcher.find()) {
count++;
System.out.println(matcher.group().trim()); //If want to display the matched words
}
return count;
}

class HelloWorld {
public static void main(String[] args) {
String str = "User is in for an interview";
int counter=0;
String arrStr[] = str.split(" ");
for (int i = 0; i< arrStr.length; i++){
String charStr = arrStr[i];
for(int j=0; j<charStr.length(); j++) {
if(charStr.charAt(j) =='i') {
counter++;
}
}
}
System.out.println("i " + counter);
}
}

public class CountWords {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string :");
String str = sc.nextLine();
System.out.println("length is string is :"+str.length());
int worldCount = 1;
for(int i=0; i<str.length(); i++){
if(str.charAt(i) == ' '){
worldCount++;
}
}
System.out.println(worldCount);
}
}

The full program working is:
public class main {
public static void main(String[] args) {
logicCounter counter1 = new logicCounter();
counter1.counter("I am trying to make a program on word count which I have partially made and it is giving the correct result but the moment I enter space or more than one space in the string, the result of word count show wrong results because I am counting words on the basis of spaces used. I need help if there is a solution in a way that no matter how many spaces are I still get the correct result. I am mentioning the code below.");
}
}
public class logicCounter {
public void counter (String str) {
String str1 = str;
boolean space= true;
int i;
for ( i = 0; i < str1.length(); i++) {
if (str1.charAt(i) == ' ') {
space=true;
} else {
i++;
}
}
System.out.println("there are " + i + " letters");
}
}

Related

Removing white spaces from string using loops

Hi guys I'm trying to remove white spaces using loops specifically. Heres what I've come up with so far
import java.util.Scanner;
public class Q2 {
public static void main(String[] args) {
String input = "";
char noSpace = ' ';
Scanner scan = new Scanner(System.in);
input = scan.nextLine();
System.out.println(input);
for (int i = 0; i < input.length(); i++) { //search from right to left
for (int j = input.length(); j != -1; j--) { //search from left to right
if (input.charAt(i) == noSpace) { //if there is a space move position of i and j
i++;
j--;
}
}
System.out.println(input);
I am still quite new to java, any suggestions would be great thanks!
Try this one:
public class RemoveWhiteSpace {
public static void main(String[] args) {
String str = "Hello World... Hai... How are you? .";
for(Character c : str.toCharArray()) {
if(!Character.isWhitespace(c)) // Check if not white space print the char
System.out.print(c);
}
}
}
Why you do not use regular expressions? replaceAll("\\s","") removes all whitespaces. Also you can remove other non visible symbols, such as \tab etc.
Look at docs.oracle.com for more info
And a combination of themes...
StringBuilder result = new StringBuilder(64);
String str = "sample test";
for (Character c : str.toCharArray()) {
if (!Character.isWhitespace(c)) {
result.append(c);
}
}
System.out.println(result.toString()); // toString is not required, but I've had to many people assume that StringBuilder is a String
System.out.println(str.replace(" ", ""));
System.out.println("Double spaced".replace(" ", ""));
Basically, nothing new, just runnable examples of what every body else has spoken about...
import java.util.Scanner;
public class Iterations{
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = kb.nextLine();
String temp = "";
for (int i = 0; i < s.length(); i++){ //This loops separates the string into each character
String c = s.substring(i, i+1);
if (c.equals(" ")){
System.out.print(c.trim()); //If the individual character is space then remove it with trim()
} else {
temp = temp + c; //Adds the string up into single sentence
}
}
System.out.println(temp); //Print it to have a nice line of string
}
}
I am also new to java and happen to do problems that remove spaces with only some methods and loops. Thats my solution, feel free to try it out.
public class sample {
public static void main(String[] args) {
String input = "sample test";
char noSpace = ' ';
System.out.println("String original:"+input);
for (int i = 0; i < input.length(); i++) { //search from right to left
if (input.charAt(i) != noSpace) { //if there is a space move position of i and j
System.out.print(input.charAt(i));
}
}
}
}
You've actually gone too far by keeping two loops you could do it in one only:
public static void main(String[] args) {
String input = "";
char space = ' ';
Scanner scan = new Scanner(System.in);
input = scan.nextLine();
System.out.println(input);
for (int i = 0; i < input.length(); i++) { // search from right to left char by char
if (input.charAt(i)!= space) { // if the char is not space print it.
System.out.print(input.charAt(i));
}
}
}

Reversing characters in each word in a sentence - Stack Implementation

This code is inside the main function:
Scanner input = new Scanner(System.in);
System.out.println("Type a sentence");
String sentence = input.next();
Stack<Character> stk = new Stack<Character>();
int i = 0;
while (i < sentence.length())
{
while (sentence.charAt(i) != ' ' && i < sentence.length() - 1)
{
stk.push(sentence.charAt(i));
i++;
}
stk.empty();
i++;
}
And this is the empty() function:
public void empty()
{
while (this.first != null)
System.out.print(this.pop());
}
It doesn't work properly, as by typing example sentence I am getting this output: lpmaxe. The first letter is missing and the loop stops instead of counting past the space to the next part of the sentence.
I am trying to achieve this:
This is a sentence ---> sihT si a ecnetnes
Per modifications to the original post, where the OP is now indicating that his goal is to reverse the letter order of the words within a sentence, but to leave the words in their initial positions.
The simplest way to do this, I think, is to make use of the String split function, iterate through the words, and reverse their orders.
String[] words = sentence.split(" "); // splits on the space between words
for (int i = 0; i < words.length; i++) {
String word = words[i];
System.out.print(reverseWord(word));
if (i < words.length-1) {
System.out.print(" "); // space after all words but the last
}
}
Where the method reverseWord is defined as:
public String reverseWord(String word) {
for( int i = 0; i < word.length(); i++) {
stk.push(word.charAt(i));
}
return stk.empty();
}
And where the empty method has been changed to:
public String empty() {
String stackWord = "";
while (this.first != null)
stackWord += this.pop();
return stackWord;
}
Original response
The original question indicated that the OP wanted to completely reverse the sentence.
You've got a double-looping construct where you don't really need it.
Consider this logic:
Read each character from the input string and push that character to the stack
When the input string is empty, pop each character from the stack and print it to screen.
So:
for( int i = 0; i < sentence.length(); i++) {
stk.push(sentence.charAt(i));
}
stk.empty();
I assume that what you want your code to do is to reverse each word in turn, not the entire string. So, given the input example sentence you want it to output elpmaxe ecnetnes not ecnetnes elpmaxe.
The reason that you see lpmaxe instead of elpmaxe is because your inner while-loop doesn't process the last character of the string since you have i < sentence.length() - 1 instead of i < sentence.length(). The reason that you only see a single word is because your sentence variable consists only of the first token of the input. This is what the method Scanner.next() does; it reads the next (by default) space-delimited token.
If you want to input a whole sentence, wrap up System.in as follows:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
and call reader.readLine().
Hope this helps.
Assuming you've already got your input in sentence and the Stack object is called stk, here's an idea:
char[] tokens = sentence.toCharArray();
for (char c : tokens) {
if (c == ' ') {
stk.empty();
System.out.print(c);
} else {
stk.add(c);
}
}
Thus, it will scan through one character at a time. If we hit a space character, we'll assume we've hit the end of a word, spit out that word in reverse, print that space character, then continue. Otherwise, we'll add the character to the stack and continue building the current word. (If you want to also allow punctuation like periods, commas, and the like, change if (c == ' ') { to something like if (c == ' ' || c == '.' || c == ',') { and so on.)
As for why you're only getting one word, darrenp already pointed it out. (Personally, I'd use a Scanner instead of a BufferedReader unless speed is an issue, but that's just my opinion.)
import java.util.StringTokenizer;
public class stringWork {
public static void main(String[] args) {
String s1 = "Hello World";
s1 = reverseSentence(s1);
System.out.println(s1);
s1 = reverseWord(s1);
System.out.println(s1);
}
private static String reverseSentence(String s1){
String s2 = "";
for(int i=s1.length()-1;i>=0;i--){
s2 += s1.charAt(i);
}
return s2;
}
private static String reverseWord(String s1){
String s2 = "";
StringTokenizer st = new StringTokenizer(s1);
while (st.hasMoreTokens()) {
s2 += reverseSentence(st.nextToken());
s2 += " ";
}
return s2;
}
}
public class ReverseofeachWordinaSentance {
/**
* #param args
*/
public static void main(String[] args) {
String source = "Welcome to the word reversing program";
for (String str : source.split(" ")) {
System.out.print(new StringBuilder(str).reverse().toString());
System.out.print(" ");
}
System.out.println("");
System.out.println("------------------------------------ ");
String original = "Welcome to the word reversing program";
wordReverse(original);
System.out.println("Orginal Sentence :::: "+original);
System.out.println("Reverse Sentence :::: "+wordReverse(original));
}
public static String wordReverse(String original){
StringTokenizer string = new StringTokenizer(original);
Stack<Character> charStack = new Stack<Character>();
while (string.hasMoreTokens()){
String temp = string.nextToken();
for (int i = 0; i < temp.length(); i ++){
charStack.push(temp.charAt(i));
}
charStack.push(' ');
}
StringBuilder result = new StringBuilder();
while(!charStack.empty()){
result.append(charStack.pop());
}
return result.toString();
}
}
public class reverseStr {
public static void main(String[] args) {
String testsa[] = { "", " ", " ", "a ", " a", " aa bd cs " };
for (String tests : testsa) {
System.out.println(tests + "|" + reverseWords2(tests) + "|");
}
}
public static String reverseWords2(String s) {
String[] sa;
String out = "";
sa = s.split(" ");
for (int i = 0; i < sa.length; i++) {
String word = sa[sa.length - 1 - i];
// exclude "" in splited array
if (!word.equals("")) {
//add space between two words
out += word + " ";
}
}
//exclude the last space and return when string is void
int n = out.length();
if (n > 0) {
return out.substring(0, out.length() - 1);
} else {
return "";
}
}
}
This can pass in leetcode

Count words in a string method?

I was wondering how I would write a method to count the number of words in a java string only by using string methods like charAt, length, or substring.
Loops and if statements are okay!
I really appreciate any help I can get! Thanks!
This would work even with multiple spaces and leading and/or trailing spaces and blank lines:
String trim = s.trim();
if (trim.isEmpty())
return 0;
return trim.split("\\s+").length; // separate string around spaces
More info about split here.
public static int countWords(String s){
int wordCount = 0;
boolean word = false;
int endOfLine = s.length() - 1;
for (int i = 0; i < s.length(); i++) {
// if the char is a letter, word = true.
if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
word = true;
// if char isn't a letter and there have been letters before,
// counter goes up.
} else if (!Character.isLetter(s.charAt(i)) && word) {
wordCount++;
word = false;
// last word of String; if it doesn't end with a non letter, it
// wouldn't count without this.
} else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}
Hi I just figured out with StringTokenizer like this:
String words = "word word2 word3 word4";
StringTokenizer st = new Tokenizer(words);
st.countTokens();
Simply use ,
str.split("\\w+").length ;
public static int countWords(String str){
if(str == null || str.isEmpty())
return 0;
int count = 0;
for(int e = 0; e < str.length(); e++){
if(str.charAt(e) != ' '){
count++;
while(str.charAt(e) != ' ' && e < str.length()-1){
e++;
}
}
}
return count;
}
private static int countWordsInSentence(String input) {
int wordCount = 0;
if (input.trim().equals("")) {
return wordCount;
}
else {
wordCount = 1;
}
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
String str = new String("" + ch);
if (i+1 != input.length() && str.equals(" ") && !(""+ input.charAt(i+1)).equals(" ")) {
wordCount++;
}
}
return wordCount;
}
Use
myString.split("\\s+");
This will work.
There is a Simple Solution You can Try this code
String s = "hju vg jhdgsf dh gg g g g ";
String[] words = s.trim().split("\\s+");
System.out.println("count is = "+(words.length));
public static int countWords(String input) {
int wordCount = 0;
boolean isBlankSet = false;
input = input.trim();
for (int j = 0; j < input.length(); j++) {
if (input.charAt(j) == ' ')
isBlankSet = true;
else {
if (isBlankSet) {
wordCount++;
isBlankSet = false;
}
}
}
return wordCount + 1;
}
Algo in O(N)
count : 0;
if(str[0] == validChar ) :
count++;
else :
for i = 1 ; i < sizeOf(str) ; i++ :
if(str[i] == validChar AND str[i-1] != validChar)
count++;
end if;
end for;
end if;
return count;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multiset;
String str="Simple Java Word Count count Count Program";
Iterable<String> words = Splitter.on(" ").trimResults().split(str);
//google word counter
Multiset<String> wordsMultiset = HashMultiset.create();
for (String string : words) {
wordsMultiset.add(string.toLowerCase());
}
Set<String> result = wordsMultiset.elementSet();
for (String string : result) {
System.out.println(string+" X "+wordsMultiset.count(string));
}
add at the pom.xml
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>r09</version>
</dependency>
Counting Words in a String:
This might also help -->
package data.structure.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CountWords {
public static void main(String[] args) throws IOException {
// Couting number of words in a string
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter Your String");
String input = br.readLine();
char[] arr = input.toCharArray();
int i = 0;
boolean notCounted = true;
int counter = 0;
while (i < arr.length) {
if (arr[i] != ' ') {
if (notCounted) {
notCounted = false;
counter++;
}
} else {
notCounted = true;
}
i++;
}
System.out.println("words in the string are : " + counter);
}
}
public class TestStringCount {
public static void main(String[] args) {
int count=0;
boolean word= false;
String str = "how ma ny wo rds are th ere in th is sente nce";
char[] ch = str.toCharArray();
for(int i =0;i<ch.length;i++){
if(!(ch[i]==' ')){
for(int j=i;j<ch.length;j++,i++){
if(!(ch[j]==' ')){
word= true;
if(j==ch.length-1){
count++;
}
continue;
}
else{
if(word){
count++;
}
word = false;
}
}
}
else{
continue;
}
}
System.out.println("there are "+(count)+" words");
}
}
import java.util.;
import java.io.;
public class Main {
public static void main(String[] args) {
File f=new File("src/MyFrame.java");
String value=null;
int i=0;
int j=0;
int k=0;
try {
Scanner in =new Scanner(f);
while(in.hasNextLine())
{
String a=in.nextLine();
k++;
char chars[]=a.toCharArray();
i +=chars.length;
}
in.close();
Scanner in2=new Scanner(f);
while(in2.hasNext())
{
String b=in2.next();
System.out.println(b);
j++;
}
in2.close();
System.out.println("the number of chars is :"+i);
System.out.println("the number of words is :"+j);
System.out.println("the number of lines is :"+k);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
My idea of that program is that:
package text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CoutingWords {
public static void main(String[] args) throws IOException {
String str;
int cWords = 1;
char ch;
BufferedReader buffor = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter text: ");
str = buffor.readLine();
for(int i =0; i<str.length(); i++){
ch = str.charAt(i);
if(Character.isWhitespace(ch)){ cWords++; }
}
System.out.println("There are " + (int)cWords +" words.");
}
}
I'm new to stackoverflow but I hope my code helps:
private int numOfWordsInLineCounter(String line){
int words = 0;
for(int i = 1 ; i<line.length();i++){
Character ch = line.charAt(i-1);
Character bch = line.charAt(i);
if(Character.isLetterOrDigit(ch) == true && Character.isLetterOrDigit(bch)== false ) words++;
if(i == line.length()-1 && Character.isLetterOrDigit(bch))words++;
}
return words;
}
A string phrase normaly has words separated by space. Well you can split the phrase using the spaces as separating characters and count them as follows.
import java.util.HashMap;
import java.util.Map;
public class WordCountMethod {
public static void main (String [] args){
Map<String, Integer>m = new HashMap<String, Integer>();
String phrase = "hello my name is John I repeat John";
String [] array = phrase.split(" ");
for(int i =0; i < array.length; i++){
String word_i = array[i];
Integer ci = m.get(word_i);
if(ci == null){
m.put(word_i, 1);
}
else m.put(word_i, ci+1);
}
for(String s : m.keySet()){
System.out.println(s+" repeats "+m.get(s));
}
}
}
Taking the chosen answer as a starting point the following deals with a few English language issues including hyphenated words, apostrophes for possessives and shortenings, numbers and also any characters outside of UTF-16:
public static int countWords(final String s) {
int wordCount = 0;
boolean word = false;
final int endOfLine = s.length() - 1;
for (int i = 0; i < s.length(); i++) {
// if the char is a letter, word = true.
if (isWordCharacter(s, i) && i != endOfLine) {
word = true;
// if char isn't a letter and there have been letters before,
// counter goes up.
} else if (!isWordCharacter(s, i) && word) {
wordCount++;
word = false;
// last word of String; if it doesn't end with a non letter, it
// wouldn't count without this.
} else if (isWordCharacter(s, i) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}
private static boolean isWordCharacter(final String s, final int i) {
final char ch = s.charAt(i);
return Character.isLetterOrDigit(ch)
|| ch == '\''
|| Character.getType(ch) == Character.DASH_PUNCTUATION
|| Character.isSurrogate(ch);
}
I just put this together. The incrementer in the wordCount() method is a bit inelegant to me, but it works.
import java.util.*;
public class WordCounter {
private String word;
private int numWords;
public int wordCount(String wrd) {
StringTokenizer token = new StringTokenizer(wrd, " ");
word = token.nextToken();
numWords = token.countTokens();
numWords++;
return numWords;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userWord;
WordCounter wc = new WordCounter();
System.out.println("Enter a sentence.");
userWord = input.nextLine();
wc.wordCount(userWord);
System.out.println("You sentence was " + wc.numWords + " words long.");
}
}
create variable count, state. initialize variables
if space is present keep count as it is else increase count.
for eg:
if (string.charAt(i) == ' ' ) {
state = 0;
} else if (state == 0) {
state = 1;
count += 1;
lambda, in which splitting and storing of the counted words is dispensed withand only counting is done
String text = "counting w/o apostrophe's problems or consecutive spaces";
int count = text.codePoints().boxed().collect(
Collector.of(
() -> new int[] {0, 0},
(a, c) -> {
if( ".,; \t".indexOf( c ) >= 0 )
a[1] = 0;
else if( a[1]++ == 0 ) a[0]++;
}, (a, b) -> {a[0] += b[0]; return( a );},
a -> a[0] ) );
gets: 7
works as a status machine that counts the transitions from spacing characters .,; \t to words
if(str.isEmpty() || str.trim().length() == 0){
return 0;
}
return (str.trim().split("\\s+").length);
String a = "Some String";
int count = 0;
for (int i = 0; i < a.length(); i++) {
if (Character.isWhitespace(a.charAt(i))) {
count++;
}
}
System.out.println(count+1);
It will count white spaces. However, If we add 1 in count , we can get exact words.

I want to split string without using split function?

I want to split string without using split . can anybody solve my problem I am tried but
I cannot find the exact logic.
Since this seems to be a task designed as coding practice, I'll only guide. No code for you, sir, though the logic and the code aren't that far separated.
You will need to loop through each character of the string, and determine whether or not the character is the delimiter (comma or semicolon, for instance). If not, add it to the last element of the array you plan to return. If it is the delimiter, create a new empty string as the array's last element to start feeding your characters into.
I'm going to assume that this is homework, so I will only give snippets as hints:
Finding indices of all occurrences of a given substring
Here's an example of using indexOf with the fromIndex parameter to find all occurrences of a substring within a larger string:
String text = "012ab567ab0123ab";
// finding all occurrences forward: Method #1
for (int i = text.indexOf("ab"); i != -1; i = text.indexOf("ab", i+1)) {
System.out.println(i);
} // prints "3", "8", "14"
// finding all occurrences forward: Method #2
for (int i = -1; (i = text.indexOf("ab", i+1)) != -1; ) {
System.out.println(i);
} // prints "3", "8", "14"
String API links
int indexOf(String, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If no such occurrence exists, -1 is returned.
Related questions
Searching for one string in another string
Extracting substrings at given indices out of a string
This snippet extracts substring at given indices out of a string and puts them into a List<String>:
String text = "0123456789abcdefghij";
List<String> parts = new ArrayList<String>();
parts.add(text.substring(0, 5));
parts.add(text.substring(3, 7));
parts.add(text.substring(9, 13));
parts.add(text.substring(18, 20));
System.out.println(parts); // prints "[01234, 3456, 9abc, ij]"
String[] partsArray = parts.toArray(new String[0]);
Some key ideas:
Effective Java 2nd Edition, Item 25: Prefer lists to arrays
Works especially nicely if you don't know how many parts there'll be in advance
String API links
String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.
Related questions
Fill array with List data
You do now that most of the java standard libraries are open source
In this case you can start here
Use String tokenizer to split strings in Java without split:
import java.util.StringTokenizer;
public class tt {
public static void main(String a[]){
String s = "012ab567ab0123ab";
String delims = "ab ";
StringTokenizer st = new StringTokenizer(s, delims);
System.out.println("No of Token = " + st.countTokens());
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
This is the right answer
import java.util.StringTokenizer;
public class tt {
public static void main(String a[]){
String s = "012ab567ab0123ab";
String delims = "ab ";
StringTokenizer st = new StringTokenizer(s, delims);
System.out.println("No of Token = " + st.countTokens());
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
/**
* My method split without javas split.
* Return array with words after mySplit from two texts;
* Uses trim.
*/
public class NoJavaSplit {
public static void main(String[] args) {
String text1 = "Some text for example ";
String text2 = " Second sentences ";
System.out.println(Arrays.toString(mySplit(text1, text2)));
}
private static String [] mySplit(String text1, String text2) {
text1 = text1.trim() + " " + text2.trim() + " ";
char n = ' ';
int massValue = 0;
for (int i = 0; i < text1.length(); i++) {
if (text1.charAt(i) == n) {
massValue++;
}
}
String[] splitArray = new String[massValue];
for (int i = 0; i < splitArray.length; ) {
for (int j = 0; j < text1.length(); j++) {
if (text1.charAt(j) == n) {
splitArray[i] = text1.substring(0, j);
text1 = text1.substring(j + 1, text1.length());
j = 0;
i++;
}
}
return splitArray;
}
return null;
}
}
you can try, the way i did `{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
for(int i = 0; i <str.length();i++) {
if(str.charAt(i)==' ') { // whenever it found space it'll create separate words from string
System.out.println();
continue;
}
System.out.print(str.charAt(i));
}
sc.close();
}`
The logic is: go through the whole string starting from first character and whenever you find a space copy the last part to a new string.. not that hard?
The way to go is to define the function you need first. In this case, it would probably be:
String[] split(String s, String separator)
The return type doesn't have to be an array. It can also be a list:
List<String> split(String s, String separator)
The code would then be roughly as follows:
start at the beginning
find the next occurence of the delimiter
the substring between the end of the previous delimiter and the start of the current delimiter is added to the result
continue with step 2 until you have reached the end of the string
There are many fine points that you need to consider:
What happens if the string starts or ends with the delimiter?
What if multiple delimiters appear next to each other?
What should be the result of splitting the empty string? (1 empty field or 0 fields)
You can do it using Java standard libraries.
Say the delimiter is : and
String s = "Harry:Potter"
int a = s.find(delimiter);
and then add
s.substring(start, a)
to a new String array.
Keep doing this till your start < string length
Should be enough I guess.
public class MySplit {
public static String[] mySplit(String text,String delemeter){
java.util.List<String> parts = new java.util.ArrayList<String>();
text+=delemeter;
for (int i = text.indexOf(delemeter), j=0; i != -1;) {
parts.add(text.substring(j,i));
j=i+delemeter.length();
i = text.indexOf(delemeter,j);
}
return parts.toArray(new String[0]);
}
public static void main(String[] args) {
String str="012ab567ab0123ab";
String delemeter="ab";
String result[]=mySplit(str,delemeter);
for(String s:result)
System.out.println(s);
}
}
public class WithoutSpit_method {
public static void main(String arg[])
{
char[]str;
String s="Computer_software_developer_gautam";
String s1[];
for(int i=0;i<s.length()-1;)
{
int lengh=s.indexOf("_",i);
if(lengh==-1)
{
lengh=s.length();
}
System.out.print(" "+s.substring(i,lengh));
i=lengh+1;
}
}
}
Result: Computer software developer gautam
Here is my way of doing with Scanner;
import java.util.Scanner;
public class spilt {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the String to be Spilted : ");
String st = input.nextLine();
Scanner str = new Scanner(st);
while (str.hasNext())
{
System.out.println(str.next());
}
}
}
Hope it Helps!!!!!
public class StringWitoutPre {
public static void main(String[] args) {
String str = "md taufique reja";
int len = str.length();
char ch[] = str.toCharArray();
String tmp = " ";
boolean flag = false;
for (int i = 0; i < str.length(); i++) {
if (ch[i] != ' ') {
tmp = tmp + ch[i];
flag = false;
} else {
flag = true;
}
if (flag || i == len - 1) {
System.out.println(tmp);
tmp = " ";
}
}
}
}
In Java8 we can use Pattern and get the things done in more easy way. Here is the code.
package com.company;
import java.util.regex.Pattern;
public class umeshtest {
public static void main(String a[]) {
String ss = "I'm Testing and testing the new feature";
Pattern.compile(" ").splitAsStream(ss).forEach(s -> System.out.println(s));
}
}
static void splitString(String s, int index) {
char[] firstPart = new char[index];
char[] secondPart = new char[s.length() - index];
int j = 0;
for (int i = 0; i < s.length(); i++) {
if (i < index) {
firstPart[i] = s.charAt(i);
} else {
secondPart[j] = s.charAt(i);
if (j < s.length()-index) {
j++;
}
}
}
System.out.println(firstPart);
System.out.println(secondPart);
}
import java.util.Scanner;
public class Split {
static Scanner in = new Scanner(System.in);
static void printArray(String[] array){
for (int i = 0; i < array.length; i++) {
if(i!=array.length-1)
System.out.print(array[i]+",");
else
System.out.println(array[i]);
}
}
static String delimeterTrim(String str){
char ch = str.charAt(str.length()-1);
if(ch=='.'||ch=='!'||ch==';'){
str = str.substring(0,str.length()-1);
}
return str;
}
private static String [] mySplit(String text, char reg, boolean delimiterTrim) {
if(delimiterTrim){
text = delimeterTrim(text);
}
text = text.trim() + " ";
int massValue = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == reg) {
massValue++;
}
}
String[] splitArray = new String[massValue];
for (int i = 0; i < splitArray.length; ) {
for (int j = 0; j < text.length(); j++) {
if (text.charAt(j) == reg) {
splitArray[i] = text.substring(0, j);
text = text.substring(j + 1, text.length());
j = 0;
i++;
}
}
return splitArray;
}
return null;
}
public static void main(String[] args) {
System.out.println("Enter the sentence :");
String text = in.nextLine();
//System.out.println("Enter the regex character :");
//char regex = in.next().charAt(0);
System.out.println("Do you want to trim the delimeter ?");
String delch = in.next();
boolean ch = false;
if(delch.equalsIgnoreCase("yes")){
ch = true;
}
System.out.println("Output String array is : ");
printArray(mySplit(text,' ',ch));
}
}
Split a string without using split()
static String[] splitAString(String abc, char splitWith){
char[] ch=abc.toCharArray();
String temp="";
int j=0,length=0,size=0;
for(int i=0;i<abc.length();i++){
if(splitWith==abc.charAt(i)){
size++;
}
}
String[] arr=new String[size+1];
for(int i=0;i<ch.length;i++){
if(length>j){
j++;
temp="";
}
if(splitWith==ch[i]){
length++;
}else{
temp +=Character.toString(ch[i]);
}
arr[j]=temp;
}
return arr;
}
public static void main(String[] args) {
String[] arr=splitAString("abc-efg-ijk", '-');
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
}
You cant split with out using split(). Your only other option is to get the strings char indexes and and get sub strings.

How to upper case every first letter of word in a string? [duplicate]

This question already has answers here:
How to capitalize the first character of each word in a string
(51 answers)
Closed 3 years ago.
I have a string: "hello good old world" and i want to upper case every first letter of every word, not the whole string with .toUpperCase(). Is there an existing java helper which does the job?
Have a look at ACL WordUtils.
WordUtils.capitalize("your string") == "Your String"
Here is the code
String source = "hello good old world";
StringBuffer res = new StringBuffer();
String[] strArr = source.split(" ");
for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str).append(" ");
}
System.out.print("Result: " + res.toString().trim());
sString = sString.toLowerCase();
sString = Character.toString(sString.charAt(0)).toUpperCase()+sString.substring(1);
i dont know if there is a function but this would do the job in case there is no exsiting one:
String s = "here are a bunch of words";
final StringBuilder result = new StringBuilder(s.length());
String[] words = s.split("\\s");
for(int i=0,l=words.length;i<l;++i) {
if(i>0) result.append(" ");
result.append(Character.toUpperCase(words[i].charAt(0)))
.append(words[i].substring(1));
}
import org.apache.commons.lang.WordUtils;
public class CapitalizeFirstLetterInString {
public static void main(String[] args) {
// only the first letter of each word is capitalized.
String wordStr = WordUtils.capitalize("this is first WORD capital test.");
//Capitalize method capitalizes only first character of a String
System.out.println("wordStr= " + wordStr);
wordStr = WordUtils.capitalizeFully("this is first WORD capital test.");
// This method capitalizes first character of a String and make rest of the characters lowercase
System.out.println("wordStr = " + wordStr );
}
}
Output :
This Is First WORD Capital Test.
This Is First Word Capital Test.
Here's a very simple, compact solution. str contains the variable of whatever you want to do the upper case on.
StringBuilder b = new StringBuilder(str);
int i = 0;
do {
b.replace(i, i + 1, b.substring(i,i + 1).toUpperCase());
i = b.indexOf(" ", i) + 1;
} while (i > 0 && i < b.length());
System.out.println(b.toString());
It's best to work with StringBuilder because String is immutable and it's inefficient to generate new strings for each word.
Trying to be more memory efficient than splitting the string into multiple strings, and using the strategy shown by Darshana Sri Lanka. Also, handles all white space between words, not just the " " character.
public static String UppercaseFirstLetters(String str)
{
boolean prevWasWhiteSp = true;
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (Character.isLetter(chars[i])) {
if (prevWasWhiteSp) {
chars[i] = Character.toUpperCase(chars[i]);
}
prevWasWhiteSp = false;
} else {
prevWasWhiteSp = Character.isWhitespace(chars[i]);
}
}
return new String(chars);
}
String s = "java is an object oriented programming language.";
final StringBuilder result = new StringBuilder(s.length());
String words[] = s.split("\\ "); // space found then split it
for (int i = 0; i < words.length; i++)
{
if (i > 0){
result.append(" ");
}
result.append(Character.toUpperCase(words[i].charAt(0))).append(
words[i].substring(1));
}
System.out.println(result);
Output: Java Is An Object Oriented Programming Language.
Also you can take a look into StringUtils library. It has a bunch of cool stuff.
My code after reading a few above answers.
/**
* Returns the given underscored_word_group as a Human Readable Word Group.
* (Underscores are replaced by spaces and capitalized following words.)
*
* #param pWord
* String to be made more readable
* #return Human-readable string
*/
public static String humanize2(String pWord)
{
StringBuilder sb = new StringBuilder();
String[] words = pWord.replaceAll("_", " ").split("\\s");
for (int i = 0; i < words.length; i++)
{
if (i > 0)
sb.append(" ");
if (words[i].length() > 0)
{
sb.append(Character.toUpperCase(words[i].charAt(0)));
if (words[i].length() > 1)
{
sb.append(words[i].substring(1));
}
}
}
return sb.toString();
}
import java.util.Scanner;
public class CapitolizeOneString {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print(" Please enter Your word = ");
String str=scan.nextLine();
printCapitalized( str );
} // end main()
static void printCapitalized( String str ) {
// Print a copy of str to standard output, with the
// first letter of each word in upper case.
char ch; // One of the characters in str.
char prevCh; // The character that comes before ch in the string.
int i; // A position in str, from 0 to str.length()-1.
prevCh = '.'; // Prime the loop with any non-letter character.
for ( i = 0; i < str.length(); i++ ) {
ch = str.charAt(i);
if ( Character.isLetter(ch) && ! Character.isLetter(prevCh) )
System.out.print( Character.toUpperCase(ch) );
else
System.out.print( ch );
prevCh = ch; // prevCh for next iteration is ch.
}
System.out.println();
}
} // end class
public class WordChangeInCapital{
public static void main(String[] args)
{
String s="this is string example";
System.out.println(s);
//this is input data.
//this example for a string where each word must be started in capital letter
StringBuffer sb=new StringBuffer(s);
int i=0;
do{
b.replace(i,i+1,sb.substring(i,i+1).toUpperCase());
i=b.indexOf(" ",i)+1;
} while(i>0 && i<sb.length());
System.out.println(sb.length());
}
}
package com.raj.samplestring;
/**
* #author gnagara
*/
public class SampleString {
/**
* #param args
*/
public static void main(String[] args) {
String[] stringArray;
String givenString = "ramu is Arr Good boy";
stringArray = givenString.split(" ");
for(int i=0; i<stringArray.length;i++){
if(!Character.isUpperCase(stringArray[i].charAt(0))){
Character c = stringArray[i].charAt(0);
Character change = Character.toUpperCase(c);
StringBuffer ss = new StringBuffer(stringArray[i]);
ss.insert(0, change);
ss.deleteCharAt(1);
stringArray[i]= ss.toString();
}
}
for(String e:stringArray){
System.out.println(e);
}
}
}
Here is an easy solution:
public class CapitalFirstLetters {
public static void main(String[] args) {
String word = "it's java, baby!";
String[] wordSplit;
String wordCapital = "";
wordSplit = word.split(" ");
for (int i = 0; i < wordSplit.length; i++) {
wordCapital = wordSplit[i].substring(0, 1).toUpperCase() + wordSplit[i].substring(1) + " ";
}
System.out.println(wordCapital);
}}
public String UpperCaseWords(String line)
{
line = line.trim().toLowerCase();
String data[] = line.split("\\s");
line = "";
for(int i =0;i< data.length;i++)
{
if(data[i].length()>1)
line = line + data[i].substring(0,1).toUpperCase()+data[i].substring(1)+" ";
else
line = line + data[i].toUpperCase();
}
return line.trim();
}
So much simpler with regexes:
Pattern spaces=Pattern.compile("\\s+[a-z]");
Matcher m=spaces.matcher(word);
StringBuilder capitalWordBuilder=new StringBuilder(word.substring(0,1).toUpperCase());
int prevStart=1;
while(m.find()) {
capitalWordBuilder.append(word.substring(prevStart,m.end()-1));
capitalWordBuilder.append(word.substring(m.end()-1,m.end()).toUpperCase());
prevStart=m.end();
}
capitalWordBuilder.append(word.substring(prevStart,word.length()));
Output for input: "this sentence Has Weird caps"
This Sentence Has Weird Caps

Categories

Resources