2011-05-03 19 views
22

Me preguntaba cómo escribiría un método para contar el número de palabras en una cadena java solo mediante el uso de métodos de cadena como charAt, longitud o subcadena.¿Contar palabras en un método de cadena?

¡Loops y si las declaraciones son correctas!

¡Realmente agradezco cualquier ayuda que pueda obtener! ¡Gracias!

+0

¿Es esta tarea? – Trufa

+1

¡No, solo un poco de práctica de cuerdas extra! ¡Gracias amigo! –

+0

@ user667926: bueno, ¡buena suerte! – Trufa

Respuesta

19
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; 
} 
+0

Esto funciona muy bien (con puntuación también). –

+1

Debe tener en cuenta los apóstrofos y las comillas, y otros caracteres especiales. – user1159819

60

Esto funcionaría incluso con múltiples espacios y principales y/o finales espacios y líneas en blanco:

String trim = s.trim(); 
if (trim.isEmpty()) 
    return 0; 
return trim.split("\\s+").length; // separate string around spaces 

Espero que ayude. Más información sobre dividida here.

+0

Pequeña corrección. La última línea debería ser 'return words.length;' – Leigh

+5

Usaría \\ W aquí en lugar de \\ s, porque podría tener algo más que espacio separando palabras. – Trejkaz

+0

Corto, dulce y efectivo. – bobanahalf

1
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; 
} 
0

Uso

myString.split("\\s+"); 

Esto funcionará.

0

Algo en 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; 
2
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; 
    } 
0
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");  
    } 
} 
0
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> 
0

Contar palabras de una cadena:
Esto también podría ayudar ->

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

} 
+0

Realmente necesita agregar algún tipo de explicación más allá del código básico. –

+0

no estoy seguro de qué agregar. Creo que el código en sí es bastante explicativo. –

5

simplemente usar ,

str.split("\\w+").length ; 
-1
if(str.isEmpty() || str.trim().length() == 0){ 
    return 0; 
} 
return (str.trim().split("\\s+").length); 
10

Hola acabo de descubrir con StringTokenizer así: java.util

String words = "word word2 word3 word4"; 
StringTokenizer st = new Tokenizer(words); 
st.countTokens(); 
+1

Esto funciona, pero no es un método String, usa una clase StringTokenizer por separado. La pregunta es cómo hacer esto sin usar otras clases. –

0

importación. ; import java.io.;

public class Principal {

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(); 

} 


} 

}

0

Hay una solución simple que usted puede probar este código

String s = "hju vg jhdgsf dh gg g g g "; 

    String[] words = s.trim().split("\\s+"); 

    System.out.println("count is = "+(words.length)); 
0
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; 
    } 
+2

No solo publique respuestas de solo código. Agrega un contexto – Matt

0

Mi idea de este programa es que:

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

Soy nuevo a stackoverflow pero espero que mi código de ayuda:

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; 
} 
0

Una frase cadena normaly tiene palabras separadas por un espacio. Bueno, puedes dividir la frase usando los espacios como personajes separadores y contarlos de la siguiente manera.

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

} 
0

Tomando la respuesta elegida como punto de partida los siguientes acuerdos con algunos problemas de idioma Inglés, incluyendo palabras con guiones, apóstrofes para los posesivos y mantecas, números y también los caracteres fuera de 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); 
} 
Cuestiones relacionadas