Count if contain word

In this example, the goal is to count cells that contain a specific substring. This problem can be solved with the SUMPRODUCT function or the COUNTIF function. Both approaches are explained below. The SUMPRODUCT version can also perform a case-sensitive count.

COUNTIF function

The COUNTIF function counts cells in a range that meet supplied criteria. For example, to count the number of cells in a range that contain «apple» you can use COUNTIF like this:

=COUNTIF(range,"apple") // equal to "apple"

Notice this is an exact match. To be included in the count, a cell must contain «apple» and only «apple». If a cell contains any other characters, it will not be counted.

In the example shown, the goal is to count cells that contain specific text, meaning the text is a substring that can be anywhere in the cell. To do this, we need to use the asterisk (*) character as a wildcard. To count cells that contain the substring «apple», we can use a formula like this:

=COUNTIF(range,"*apple*")

The asterisk (*) wildcard matches zero or more characters of any kind, so this formula will count cells that contain «apple» anywhere in the cell. The formulas used in the worksheet shown follow the same pattern:

=COUNTIF(B5:B15,"*a*") // contains "a"
=COUNTIF(B5:B15,"*2*") // contains "2"
=COUNTIF(B5:B15,"*-S*") // contains "-s"
=COUNTIF(B5:B15,"*x*") // contains "x"

You can easily adjust this formula to use a cell reference in criteria. For example, if A1 contains the text you want to match, you can use:

=COUNTIF(range,"*"&A1&"*")

Inside COUNTIF, the two asterisks are concatenated to the value in A1, and the formula works as before. The COUNTIF function supports three different wildcards, see this page for more details.

Note the COUNTIF formula above won’t work if you are looking for a particular number and cells contain numeric data. This is because the wildcard automatically causes COUNTIF to look for text only (i.e. to look for «2» instead of just 2). Because a text value won’t ever be found in a true number, COUNTIF will return zero. In addition, COUNTIF is not case-sensitive, so you can’t perform a case-sensitive count. The SUMPRODUCT alternative below can handle both cases.

SUMPRODUCT function

Another way to solve this problem is with the SUMPRODUCT function and Boolean algebra. This approach has the benefit of being case-sensitive if needed. In addition, you can use this technique to find a number inside of a number, something you can’t do with COUNTIF.

To count cells that contain specific text with SUMPRODUCT, you can use the SEARCH function. SEARCH returns the position of text in a text string as a number. For example, the formula below returns 6 since the «a» appears first as the sixth character in the string:

=SEARCH( "a","The cat sat") // returns 6

If the text is not found, SEARCH returns a #VALUE! error:

=SEARCH( "x","The cat sat") // returns #VALUE!

To count cells that contain «a» in the worksheet shown with SUMPRODUCT, you can use the ISNUMBER and SEARCH functions like this:

=SUMPRODUCT(--ISNUMBER(SEARCH("a",B5:B15)))

Working from the inside out, the logical test inside SUMPRODUCT is based on SEARCH:

SEARCH("a",B5:B15)

Because the range B5:B15 contains 11 cells, the result from SEARCH is an array with 11 results:

{1;1;1;1;2;2;#VALUE!;#VALUE!;#VALUE!;#VALUE!;#VALUE!}

In this array, numbers indicate the position of «a» in cells where «a» is found. The #VALUE! errors indicate cells where «a» was not found. To convert these results into a simple array of TRUE and FALSE values, the SEARCH function is nested in the ISNUMBER function:

ISNUMBER(SEARCH("a",B5:B15))

ISNUMBER returns TRUE for any number and FALSE for errors. SEARCH delivers the array of results to ISNUMBER, and ISNUMBER converts the results to an array that contains only TRUE and FALSE values:

{TRUE;TRUE;TRUE;TRUE;TRUE;TRUE;FALSE;FALSE;FALSE;FALSE;FALSE}

In this array, TRUE corresponds to cells that contain «a» and FALSE corresponds to cells that do not contain «a». We want to count these results, but we first need to convert the TRUE and FALSE values to their numeric equivalents, 1 and 0. To do this, we use a double negative (—):

--ISNUMBER(SEARCH("a",B5:B15))

The result inside of SUMPRODUCT looks like this:

=SUMPRODUCT({1;1;1;1;1;1;0;0;0;0;0}) // returns 6

With a single array to process, SUMPRODUCT sums the array and returns 6 as a final result.

One benefit of this formula is it will find a number inside a numeric value. In addition, there is no need to use wildcards to indicate position, because SEARCH will automatically look through all text in a cell.

Case-sensitive option

For a case-sensitive count, you can replace the SEARCH function with the FIND function like this:

=SUMPRODUCT(--(ISNUMBER(FIND(text,range))))

The FIND function works just like the SEARCH function, but is case-sensitive. You can use a formula like this to count cells that contain «APPLE» and not «apple». This example provides more detail.

I am new to Java Strings the problem is that I want to count the Occurrences of a specific word in a String. Suppose that my String is:

i have a male cat. the color of male cat is Black

Now I dont want to split it as well so I want to search for a word that is «male cat». it occurs two times in my string!

What I am trying is:

int c = 0;
for (int j = 0; j < text.length(); j++) {
    if (text.contains("male cat")) {
        c += 1;
    }
}

System.out.println("counter=" + c);

it gives me 46 counter value! So whats the solution?

RamenChef's user avatar

RamenChef

5,55711 gold badges31 silver badges43 bronze badges

asked Mar 21, 2014 at 18:15

Java Nerd's user avatar

6

You can use the following code:

String in = "i have a male cat. the color of male cat is Black";
int i = 0;
Pattern p = Pattern.compile("male cat");
Matcher m = p.matcher( in );
while (m.find()) {
    i++;
}
System.out.println(i); // Prints 2

Demo

What it does?

It matches "male cat".

while(m.find())

indicates, do whatever is given inside the loop while m finds a match.
And I’m incrementing the value of i by i++, so obviously, this gives number of male cat a string has got.

Community's user avatar

answered Mar 21, 2014 at 18:22

Amit Joki's user avatar

Amit JokiAmit Joki

57.9k7 gold badges75 silver badges95 bronze badges

1

If you just want the count of "male cat" then I would just do it like this:

String str = "i have a male cat. the color of male cat is Black";
int c = str.split("male cat").length - 1;
System.out.println(c);

and if you want to make sure that "female cat" is not matched then use \b word boundaries in the split regex:

int c = str.split("\bmale cat\b").length - 1;

answered Mar 21, 2014 at 18:23

donfuxx's user avatar

donfuxxdonfuxx

11.2k6 gold badges43 silver badges75 bronze badges

2

StringUtils in apache commons-lang have CountMatches method to counts the number of occurrences of one String in another.

   String input = "i have a male cat. the color of male cat is Black";
   int occurance = StringUtils.countMatches(input, "male cat");
   System.out.println(occurance);

answered Jul 13, 2015 at 13:00

2787184's user avatar

27871842787184

3,7199 gold badges46 silver badges81 bronze badges

Java 8 version:

    public static long countNumberOfOccurrencesOfWordInString(String msg, String target) {
    return Arrays.stream(msg.split("[ ,\.]")).filter(s -> s.equals(target)).count();
}

answered Apr 16, 2015 at 15:01

Karol Król's user avatar

Karol KrólKarol Król

3,2301 gold badge33 silver badges37 bronze badges

Java 8 version.

System.out.println(Pattern.compile("\bmale cat")
            .splitAsStream("i have a male cat. the color of male cat is Black")
            .count()-1);

answered Dec 23, 2017 at 6:05

Zach Eldemire's user avatar

0

This static method does returns the number of occurrences of a string on another string.

/**
 * Returns the number of appearances that a string have on another string.
 * 
 * @param source    a string to use as source of the match
 * @param sentence  a string that is a substring of source
 * @return the number of occurrences of sentence on source 
 */
public static int numberOfOccurrences(String source, String sentence) {
    int occurrences = 0;

    if (source.contains(sentence)) {
        int withSentenceLength    = source.length();
        int withoutSentenceLength = source.replace(sentence, "").length();
        occurrences = (withSentenceLength - withoutSentenceLength) / sentence.length();
    }

    return occurrences;
}

Tests:

String source = "Hello World!";
numberOfOccurrences(source, "Hello World!");   // 1
numberOfOccurrences(source, "ello W");         // 1
numberOfOccurrences(source, "l");              // 3
numberOfOccurrences(source, "fun");            // 0
numberOfOccurrences(source, "Hello");          // 1

BTW, the method could be written in one line, awful, but it also works :)

public static int numberOfOccurrences(String source, String sentence) {
    return (source.contains(sentence)) ? (source.length() - source.replace(sentence, "").length()) / sentence.length() : 0;
}

answered Mar 21, 2014 at 18:32

Lucio's user avatar

LucioLucio

4,5833 gold badges48 silver badges75 bronze badges

using indexOf…

public static int count(String string, String substr) {
    int i;
    int last = 0;
    int count = 0;
    do {
        i = string.indexOf(substr, last);
        if (i != -1) count++;
        last = i+substr.length();
    } while(i != -1);
    return count;
}

public static void main (String[] args ){
    System.out.println(count("i have a male cat. the color of male cat is Black", "male cat"));
}

That will show: 2

Another implementation for count(), in just 1 line:

public static int count(String string, String substr) {
    return (string.length() - string.replaceAll(substr, "").length()) / substr.length() ;
}

answered Mar 21, 2014 at 18:27

Roberto's user avatar

RobertoRoberto

8,4363 gold badges42 silver badges52 bronze badges

Why not recursive ?

public class CatchTheMaleCat  {
    private static final String MALE_CAT = "male cat";
    static int count = 0;
    public static void main(String[] arg){
        wordCount("i have a male cat. the color of male cat is Black");
        System.out.println(count);
    }

    private static boolean wordCount(String str){
        if(str.contains(MALE_CAT)){
            count++;
            return wordCount(str.substring(str.indexOf(MALE_CAT)+MALE_CAT.length()));
        }
        else{
            return false;
        }
    }
}

answered Apr 17, 2015 at 6:43

zawhtut's user avatar

zawhtutzawhtut

8,3015 gold badges51 silver badges76 bronze badges

public class TestWordCount {

public static void main(String[] args) {

    int count = numberOfOccurences("Alice", "Alice in wonderland. Alice & chinki are classmates. Chinki is better than Alice.occ");
    System.out.println("count : "+count);

}

public static int numberOfOccurences(String findWord, String sentence) {

    int length = sentence.length();
    int lengthWithoutFindWord = sentence.replace(findWord, "").length();
    return (length - lengthWithoutFindWord)/findWord.length();

}

}

answered Apr 15, 2017 at 19:45

sakshi bhatia's user avatar

1

This will work

int word_count(String text,String key){
   int count=0;
   while(text.contains(key)){
      count++;
      text=text.substring(text.indexOf(key)+key.length());
   }
   return count;
}

Durgpal Singh's user avatar

answered Dec 29, 2016 at 10:36

kail95's user avatar

Replace the String that needs to be counted with empty string and then use the length without the string to calculate the number of occurrence.

public int occurrencesOf(String word)
    {
    int length = text.length();
    int lenghtofWord = word.length();
    int lengthWithoutWord = text.replace(word, "").length();
    return (length - lengthWithoutWord) / lenghtofWord ;
    }

ravthiru's user avatar

ravthiru

8,6082 gold badges41 silver badges51 bronze badges

answered Aug 11, 2017 at 2:53

Ravi Kumar's user avatar

1

Once you find the term you need to remove it from String under process so that it won’t resolve the same again, use indexOf() and substring() , you don’t need to do contains check length times

answered Mar 21, 2014 at 18:16

jmj's user avatar

jmjjmj

237k42 gold badges398 silver badges437 bronze badges

2

The string contains that string all the time when looping through it. You don’t want to ++ because what this is doing right now is just getting the length of the string if it contains » «male cat»

You need to indexOf() / substring()

Kind of get what i am saying?

answered Mar 21, 2014 at 18:21

3kings's user avatar

3kings3kings

8402 gold badges13 silver badges28 bronze badges

If you find the String you are searching for, you can go on for the length of that string (if in case you search aa in aaaa you consider it 2 times).

int c=0;
String found="male cat";
 for(int j=0; j<text.length();j++){
     if(text.contains(found)){
         c+=1;
         j+=found.length()-1;
     }
 }
 System.out.println("counter="+c);

answered Mar 21, 2014 at 18:29

AndreaTaroni86's user avatar

This should be a faster non-regex solution.
(note — Not a Java programmer)

 String str = "i have a male cat. the color of male cat is Black";
 int found  = 0;
 int oldndx = 0;
 int newndx = 0;

 while ( (newndx=str.indexOf("male cat", oldndx)) > -1 )
 {
     found++;
     oldndx = newndx+8;
 }

answered Mar 21, 2014 at 18:50

There are so many ways for the occurrence of substring and two of theme are:-

public class Test1 {
public static void main(String args[]) {
    String st = "abcdsfgh yfhf hghj gjgjhbn hgkhmn abc hadslfahsd abcioh abc  a ";
    count(st, 0, "a".length());

}

public static void count(String trim, int i, int length) {
    if (trim.contains("a")) {
        trim = trim.substring(trim.indexOf("a") + length);
        count(trim, i + 1, length);
    } else {
        System.out.println(i);
    }
}

public static void countMethod2() {
    int index = 0, count = 0;
    String inputString = "mynameiskhanMYlaptopnameishclMYsirnameisjasaiwalmyfrontnameisvishal".toLowerCase();
    String subString = "my".toLowerCase();

    while (index != -1) {
        index = inputString.indexOf(subString, index);
        if (index != -1) {
            count++;
            index += subString.length();
        }
    }
    System.out.print(count);
}}

answered Jan 23, 2017 at 17:36

Ravindra Kumar's user avatar

We can count from many ways for the occurrence of substring:-

public class Test1 {
public static void main(String args[]) {
    String st = "abcdsfgh yfhf hghj gjgjhbn hgkhmn abc hadslfahsd abcioh abc  a ";
    count(st, 0, "a".length());

}

public static void count(String trim, int i, int length) {
    if (trim.contains("a")) {
        trim = trim.substring(trim.indexOf("a") + length);
        count(trim, i + 1, length);
    } else {
        System.out.println(i);
    }
}

public static void countMethod2() {
    int index = 0, count = 0;
    String inputString = "mynameiskhanMYlaptopnameishclMYsirnameisjasaiwalmyfrontnameisvishal".toLowerCase();
    String subString = "my".toLowerCase();

    while (index != -1) {
        index = inputString.indexOf(subString, index);
        if (index != -1) {
            count++;
            index += subString.length();
        }
    }
    System.out.print(count);
}}

answered Jan 23, 2017 at 17:43

Ravindra Kumar's user avatar

I’ve got another approach here:

String description = "hello india hello india hello hello india hello";
String textToBeCounted = "hello";

// Split description using "hello", which will return 
//string array of words other than hello
String[] words = description.split("hello");

// Get number of characters words other than "hello"
int lengthOfNonMatchingWords = 0;
for (String word : words) {
    lengthOfNonMatchingWords += word.length();
}

// Following code gets length of `description` - length of all non-matching
// words and divide it by length of word to be counted
System.out.println("Number of matching words are " + 
(description.length() - lengthOfNonMatchingWords) / textToBeCounted.length());

answered Nov 15, 2017 at 12:34

Alpha's user avatar

AlphaAlpha

13.1k26 gold badges90 silver badges158 bronze badges

Complete Example here,

package com.test;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class WordsOccurances {

      public static void main(String[] args) {

            String sentence = "Java can run on many different operating "
                + "systems. This makes Java platform independent.";

            String[] words = sentence.split(" ");
            Map<String, Integer> wordsMap = new HashMap<String, Integer>();

            for (int i = 0; i<words.length; i++ ) {
                if (wordsMap.containsKey(words[i])) {
                    Integer value = wordsMap.get(words[i]);
                    wordsMap.put(words[i], value + 1);
                } else {
                    wordsMap.put(words[i], 1);
                }
            }

            /*Now iterate the HashMap to display the word with number 
           of time occurance            */

           Iterator it = wordsMap.entrySet().iterator();
           while (it.hasNext()) {
                Map.Entry<String, Integer> entryKeyValue = (Map.Entry<String, Integer>) it.next();
                System.out.println("Word : "+entryKeyValue.getKey()+", Occurance : "
                                +entryKeyValue.getValue()+" times");
           }
     }
}

answered Dec 11, 2017 at 17:25

Anil Nivargi's user avatar

Anil NivargiAnil Nivargi

1,4423 gold badges26 silver badges33 bronze badges

public class WordCount {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String scentence = "This is a treeis isis is is is";
    String word = "is";
    int wordCount = 0;
    for(int i =0;i<scentence.length();i++){
        if(word.charAt(0) == scentence.charAt(i)){
            if(i>0){
                if(scentence.charAt(i-1) == ' '){
                    if(i+word.length()<scentence.length()){
                        if(scentence.charAt(i+word.length()) != ' '){
                            continue;}
                        }
                    }
                else{
                    continue;
                }
            }
            int count = 1;
            for(int j=1 ; j<word.length();j++){
                i++;
                if(word.charAt(j) != scentence.charAt(i)){
                    break;
                }
                else{
                    count++;
                }
            }
            if(count == word.length()){
                wordCount++;
            }

        }
    }
    System.out.println("The word "+ word + " was repeated :" + wordCount);
}

}

answered Feb 15, 2018 at 18:14

Chaitanya's user avatar

1

Simple solution is here-

Below code uses HashMap as it will maintain keys and values. so here keys will be word and values will be count (occurance of a word in a given string).

public class WordOccurance 
{

 public static void main(String[] args) 
 {
    HashMap<String, Integer> hm = new HashMap<>();
    String str = "avinash pande avinash pande avinash";

    //split the word with white space       
    String words[] = str.split(" ");
    for (String word : words) 
    {   
        //If already added/present in hashmap then increment the count by 1
        if(hm.containsKey(word))    
        {           
            hm.put(word, hm.get(word)+1);
        }
        else //if not added earlier then add with count 1
        {
            hm.put(word, 1);
        }

    }
    //Iterate over the hashmap
    Set<Entry<String, Integer>> entry =  hm.entrySet();
    for (Entry<String, Integer> entry2 : entry) 
    {
        System.out.println(entry2.getKey() + "      "+entry2.getValue());
    }
}

}

answered Apr 19, 2018 at 14:12

Avinash Pande's user avatar

public int occurrencesOf(String word) {
    int length = text.length();
    int lenghtofWord = word.length();
    int lengthWithoutWord = text.replaceAll(word, "").length();
    return (length - lengthWithoutWord) / lenghtofWord ;
}

J-Alex's user avatar

J-Alex

6,72510 gold badges45 silver badges61 bronze badges

answered Jan 18, 2019 at 12:52

Koustuv Ganguly's user avatar

for scala it’s just 1 line

def numTimesOccurrenced(text:String, word:String) =text.split(word).size-1

answered Sep 28, 2020 at 4:20

Raptor0009's user avatar

Raptor0009Raptor0009

2384 silver badges14 bronze badges

Excel spreadsheet is known to be one of the best data storing and analyzing tools. Cells together make spreadsheets that consist of text and numbers. For more understanding, you have to differentiate cells filled with text.  

So, practically how would you count cells with text in Excel? You can use a few different formulas to count cells containing any text, empty cells, and cells with specific characters or just filtered cells. All these formulas can be used in Excel 2019, 2016, 2013, and 2010.  

At first, Excel spreadsheets were limited to dealing with numbers, however now we can use these sheets to store as well as modify text. Do you really want to know how many cells are filled with text in your data sheet?

For this purpose, you can use multiple functions in Excel. Depending on the situation, you can use any function.

Here you will find the tricks to count text in Excel. Let’s have a look at how you can count if a cell contains text in different conditions.

Before moving forward to learn how Excel counts cells with text, why not have a quick overview of what a Count If the function is.

COUNTIF Function

To be honest, counting cells containing text in a spreadsheet is not an easy task. That’s why the Count if the function is there to help you in this case. Using asterisk wildcards, you can count the number of cells having specific text with COUNTIF function.

The basic purpose of asterisk wildcards is to correspond to any characters or numbers. Putting them before and after any text, you can simply count the number of cells in which the text is found.  

Here is the general formula for the COUNTIF function:

=COUNTIF (Range, “*Text*”)

Example:

=COUNTIF (A2:A11, “*Class*”)

The last name “Class” when put in the asterisk, the COUNTIF formula simply calculates all string values within the range containing the name “Class.”

How to Count Number of Cells with Text in Excel

You can count if cell contains any text string or character by using two basic formulas.

Using COUNTIF Formula to Count All Cells with Text

The COUNTIF formula with an asterisk in the criteria argument is the main solution. For instance:

COUNTIF (range, “*”) (as mentioned above)

For more understanding of this formula, let’s have a look at which values are included and which are not:

Counted Values

  • Special characters
  • Cells with all kinds of text
  • Numbers formatted as text
  • Visually blank cells that have an empty string (“”), apostrophe (‘), space, or non-printing characters

Non-Counted Values

  • Numbers
  • Errors
  • Dates
  • Blank cells
  • Logical values of TRUE or FALSE

For instance, in the range A2:A10, you can count if the cell contains text, apart from dates, numbers, logical values, blank cells, and errors.

Try using one of the following formulas:

COUNTIF(A2:A10, “*”)

SUMPRODUCT(–ISTEXT(A2:A10))

SUMPRODUCT( ISTEXT(A2:A10)*1)

Count If Cell Contains Text without Spaces and Empty Strings

Using the above-mentioned formulas can help you count all cells containing any text or character in them. However, in some situations, it might be tiring and confusing as certain cells may look blank, but in reality, they are not.

Keep in mind that empty strings, spaces, apostrophes, line breaks, etc are not easily countable with the human eye. However, they are not difficult to count using formulas.

Using the COUNTIFS function will let you exclude “false positive” blank cells from the count. For instance, in the range A2:A7, you can count cells with text that overlooks the space character:

COUNTIFS(A2:A7l”*”A2:A7,”<>”)

If your target range has any formula-driven data, it might be possible that some of the formulas can ultimately be an empty string (“”). You can even ignore these empty strings by replacing “*” with “*?*” in the criteria 1 argument:

=COUNTIFS(A2:A9,”*?*”, A2:A9, “<>”)

Here the question mark shows that you need to have at least one text character. You know that an empty string does not have characters in it, and it does not meet that’s why it is not included. Also, remember that blank cells starting with an apostrophe (‘) are not included as well.

Below in the image, you can see a space in A7 cell, an apostrophe in A8, and an empty string (=””) in A9.  

How to Count IF Cells Contain Specific Text  

As you already know that COUNTIF function is best for counting all cells containing text, you can even COUNTIF cell contains specific text. Suppose, we need to count the number of times the word used “Excel” in a specific cell range:

  1. Open the spreadsheet in Excel you want to check.
  2. Click on a blank cell to enter the formula.

  1. In the blank cell, you need to type “=COUNTIF (range, criteria)”.

Using this formula will count all the number of cells having specific text within a cell range.

  1. You have to enter the cell range you need to count for the “range”. Now, add the first and last cells separated with a colon. Enter “A2: A20” to count cells.

  1. Now type “Excel” for the “Criteria.” It will help you count the number of cells using “Excel” in a certain range. Your formula will look like “=COUNTIF (A2:A20, “Excel”).

How To Count Cells with Color Text in Excel

Do you know Excel does not provide a formula to count cells with colored text?

However, still you cannot do this manually as counting all colored cells one by one is not an easy thing. By filtering the results, you can execute this process. Follow the steps given below:

  1. Go to the spreadsheet you want to analyze.

  1. Right-click a cell with the text of the color you want to count.

  1. Select “Filter,” and then “Filter by Selected Cell’s Font Color” to filter the cells with the selected text color.

  1. Get ready for counting the data range. Here is the formula if your text is from cell B2 to B20: “=SUBTOTAL (B2:B20)”

After pressing the “Enter” key, your filter will be applied and Excel will start showing the cells having that specific color and the remaining value–s will be hidden.

In the hidden rows, the “SUBTOTAL” function will not add the values. That’s why it will only count the selected color text.   

Summing Up Count If Cell Contains Text

For storing and analyzing the data, Excel is a huge platform that provides multiple functions for several problems. Both text and numbers are dealt in Excel. Around four hundred functions can use the COUNTIF function. It helps in finding the sum of cells containing specific data.  

When you’re working with large datasets in Google Sheets, you will sometimes need to count cells with text in Google Sheets. This could be names, ids, or even dates.

But can Google Sheets count cells with text?

Luckily like most other spreadsheets, you can count text in Google Sheets.

And thanks to awesome formulas in Google Sheets, this can be done in seconds. The count functions in Google spreadsheet count cells with text.

In this tutorial, I will show you a couple of scenarios where you can have google sheets count cells with text.

How to Count Cells Containing Text in Google Sheets

Here’s how to count cells containing text in Google Sheets::

  1. Select the cell where you want to display the count.
  2. Type the following formula into the cell: =COUNTA(
  3. Select the range of cells you want to count. For example, if you want to count all the cells in column A, you would use A:A as the range.
  4. Press Enter.

Using the COUNTA Function

You can also use the COUNTA Google Sheets formula to count cells with text. The COUNTA function counts the numeric values for the cells in the range that are not empty.

This includes cells with error values and empty texts, but it does not count any blank cells.

The syntax for the COUNTA function is:

COUNTA(value1, [value2], ...)

Value1  (Required):  Represents the values that you want to count.

Value2  (Optional): Represents additional values that you want to count, with a limit of 255 arguments.

To make the COUNTA function count cells with texts only instead of all the non-blank cells, you need to put in the arguments in the count function.

Here is a step-by-step guide on how to count cells with texts in Google Sheets using the COUNTA Function:

  1. Select the cell where you will put your formula.
  2. Type in the formula =COUNTA(

Type in the formula =COUNTA(

  1. Select the range you want to count.

Select the range you want to count.

  1. This will return the number of cells with any text in them.

This will return the number of cells with any text in them.

COUNTA vs COUNTIF vs LEN

The COUNTA function lets Google Sheets is like the “COUNTIF cell contains text” function, but it can also be any other value. To let Google Sheets count cells with specific text, you need to use COUNTIF functions instead. To count the number of characters in a cell, you will need to use the LEN function instead.

Using the COUNTIF Function

The COUNTIF Google Sheets formula counts cells with specific text by inputting the specified texts as the criterion.

Using the COUNTIF function for Google Sheets to count cells with text is a simple process.

COUNTIF Syntax

The syntax for the COUNTIF function is written as follows:

=COUNTIF(range, criterion)

Using this function, Google Sheets will count if contains a value in the range that meets the criterion.

  • The range, in this case, specifies to Google Sheets to count the number of cells with text
  • The criterion specifies which texts you want to be counted.

Let’s look at an example to help you understand better.

Using SUMPRODUCT Function

You can also use SUMPRODUCT to count cells with text in google sheets. This function is a useful substitute for the COUNTA function when you only want to count text and not space characters.

However, to use SUMPRODUCT to count cells with text, you’ll need to combine it with the LEN function.

SUMPRODUCT Syntax

 =SUMPRODUCT(--(LEN(range)>0))

The formula itself is pretty straight forward, and all you need to do is input the range.

  1. Click on an empty cell and input the function =SUMPRODUCT(

Click on an empty cell and input the function =SUMPRODUCT(

  1. Type LEN after the opening bracket and select it from the formula suggestions.

Type LEN after the opening bracket and select it from the formula suggestions.

  1. Select the range you want to count.

Select the range you want to count.

  1. Close the bracket and add >0

Close the bracket and add >0

This formula will return the number of cells with text.

This formula will return the number of cells with text.

Can Google Sheets Count Cells With Text With Specific Values?

Suppose you have a dataset, as shown below, and you want to quickly count the number of times the name ‘Mark’ occurs in column A.

Example spreadsheet

Below is the formula you can use to do this:

COUNTIF(A2:A13,"Mark")

Here is a step-by-step guide on how to count cells with a specific text in Google Sheets using the COUNTIF Function:

  1. Select the cell where you will put your formula.
  2. Type in the formula =COUNTIF(
  3. Select the range you want to count.
  4. Add a comma and type the word we want to count in quotation marks.
  5. Click Enter.

This will return the number of cells with the specific text in them.

COUNTIF formula to count cells with specific text in Google Sheets

Here is how this above COUNTIF formula works:

  • The first argument of this formula is the range where you have the data, In this example, it’s A2:A13 which has the names
  • The second argument is the criteria. This is what is used to check the value in the cell, and if this criterion is met, then the cell is counted. In this example, I have manually entered the name Mark in double quotes. If you have this criterion in a cell, you can use the reference here.

The above formula does a conditional count by going through all the cells in the range and counting those cells where the criterion text is present.

Note that the criterion text used in this formula is not case-sensitive. So whether you use MARK, Mark, or mark, the result would be the same.

In this example, I have used a name, but it could be any text – such as ids or numbers.

How to Count Cells That Do Not Contain a Specific Text

You can modify the COUNTIF function in Google spreadsheet count number of cells with text without using a specific text.

For example, if I have the dataset as shown below and I want to count all the cells where the name is not Mark, I can easily do this with the COUNTIF function.

Below is the formula that will give the count of all the cells where the name is not Mark:

=COUNTIF(A2:A13,"<>Mark")

COUNTIF formula to count cells that does not contain a specific text

Here is a step-by-step guide on how to count cells without a specific text in Google Sheets using the COUNTIF Function:

  1. Select the cell where you will put your formula.
  2. Type in the formula =COUNTIF(
  3. Select the range you want to count.
  4. Add a comma and type <> and the word you want to omit from the count, in our example, that’s Mark.
  5. Click Enter.

This will return the number of cells without the specific text in them.

The above formula uses the range of the cells as the first argument and the criteria used is “<>Mark”. Here the not-equal-to sign needs to be within the double quotes as well.

How to Count Cells with One of Specific Texts

In the examples above, we let Google Sheets count the number of cells with text for the entire cell content .

So if we wanted to Google Sheets count if cell contains text specified, in this case the name Mark, we used “Mark” as the criterion. This counted all the cells where the entire cell content was ‘Mark’.

But let’s say, you have a dataset of full names (or some other text) along with the name and you want to count all the cells that contain the name ‘Mark’, then you can use the above formula.

In this case, you need to use the COUNTIF function with wild card characters.

Below is the formula that will give you the count of all the cells that have the word ‘Mark’ in it.

=COUNTIF(A2:A13,"*mark*")

Here’s how:

  1. Select the cell where you will put your formula.
  2. Type in the formula =COUNTIF(
  3. Select the range you want to count.
  4. Add a comma and type the word we want to count in quotation marks. Enclose it in asterisks (*)
  5. Click Enter.

This will return the number of cells with any text in them.

Count Cells where there is a partial match

In the above function, the criterion is flanked by an asterisk symbol (*) on both sides.

As the asterisk sign (*) is a wildcard character that can represent any number of characters in a formula. This means that where this formula checks for the given condition, there could be any number of characters/words before and after the criteria.

In simple terms, if the word Mark (or whatever your criterion is) is present in the cell, this formula would count the cell.

Caution: One thing you need to remember when using the asterisk sign (*) to count if cell contains text in Google Sheets is that it would consider the condition met as soon as the criterion text is found. For example, in the above example, in case the cell contains the text Market or Marketing, these would be counted as these also contain the text ‘Mark’ – which is out criteria in the function.

In case you want to use the function for counting text in Google Sheets by checking for multiple criteria, you need to use the COUNTIFS function.

One of the questions I often get is whether you can use the COUNTIF function to count the cells with colors. Unfortunately, you can not. However, here is a tutorial where I show how you can easily filter and count cells based on color.

Frequently Asked Questions

How Do I Count a Cell Containing Text in Google Sheets?

To count a cell containing text in Google Sheets, you can use the COUNTIF function. Here’s how to do it:

  1. Select the cell where you want to display the count.
  2. Type the following formula into the cell: =COUNTA(
  3. Select the range of cells you want to count. For example, if you want to count all the cells in column A, you would use A:A as the range.
  4. Press Enter.

How Do I Count Cells with Text in a Row in Google Sheets?

To count a cell containing text in Google Sheets, you can use the COUNTIF function. Here’s how to do it:

  1. Select the cell where you want to display the count.
  2. Type the following formula into the cell: =COUNTA(
  3. Select the row of cells you want to count.
  4. Press Enter.

How Do I Count the Number of Cells that Contain Specific Text?

To count a cell containing text in Google Sheets, you can use the COUNTIF function. Here’s how to do it:

  1. Select the cell where you want to display the count.
  2. Type the following formula into the cell: =COUNTIF(
  3. Select the range of cells you want to count.
  4. Add a comma and type the specific text in quotation marks.
  5. Press Enter.

How Do I Count Cells with the Same Value in Google Sheets?

To count a cell containing text in Google Sheets, you can use the COUNTIF function. Here’s how to do it:

  1. Select the cell where you want to display the count.
  2. Type the following formula into the cell: =COUNTA(
  3. Select the range of cells you want to count. For example, if you want to count all the cells in column A, you would use A:A as the range.
  4. Press Enter.

Conclusion

Google Sheets counting cells with text is an easy topic to tackle once you know what you’re doing. In this case, you can use count functions like the COUNTA function if you want to count cells with any text and the COUNTIF Google Sheets formula to count cells with specific text.

Hopefully, you were able to follow this guide on how to count cells with text in Google Sheets and we’ve answered the question, “Can Google Sheets count cells with text”. If you still need help, please check out our comprehensive Google Sheets and Forms course.

Related:

  • How to Get the Word Count in Google Sheets
  • How To Remove Duplicates In Google Sheets
  • Count Cells IF NOT Blank (Non-Empty cells) in Google Sheets
  • Remove the First Character from a String in Google Sheets
  • Count the Number of Characters in a Cell in Google Sheets
  • IFS Function in Google Sheet
  • Count Cells based on the Cell Color in Google Sheets
Skip to content

Excel Logo

Excel If Cell Contains Text

Excel If Cell Contains Text Then

Excel If Cell Contains Text Then Formula helps you to return the output when a cell have any text or a specific text. You can check if a cell contains a some string or text  and produce something in other cell. For Example you can check if a cell A1 contains text ‘example text’  and print Yes or No in Cell B1. Following are the example Formulas to check if Cell contains text then return some thing in a Cell.

If Cell Contains Text

Here are the Excel formulas to check if Cell contains specific text then return something. This will return if there is any string or any text in given Cell. We can use this simple approach to check if a cell contains text, specific text, string,  any text using Excel If formula. We can use equals to  operator(=) to compare the strings .

If Cell Contains Text Then TRUE

Following is the Excel formula to return True if a Cell contains Specif Text. You can check a cell if there is given string in the Cell and return True or False.

=IF(ISNUMBER(FIND(“How”,A1,1)),TRUE,FALSE)

The formula will return true if it found the match, returns False of no match found.

If Cell Contains Text Then TRUE

If Cell Contains Partial Text

We can return Text If Cell Contains Partial Text. We use formula or VBA to Check Partial Text in a Cell.

Find for Case Sensitive Match:

We can check if a Cell Contains Partial Text then return something using Excel Formula. Following is a simple example to find the partial text in a given Cell. We can use if your want to make the criteria case sensitive.

=IF(ISERROR(FIND($E$1,A2,1)),”Not Found”,”Found”)

If Cell Contains Partial Text

  • Here, Find Function returns the finding position of the given string
  • Use Find function is Case Sensitive
  • IsError Function check if Find Function returns Error, that means, string not found

Search for Not Case Sensitive Match:

We can use Search function to check if Cell Contains Partial Text. Search function useful if you want to make the checking criteria Not Case Sensitive.

=IF(ISERROR(SEARCH($F$1,A2,1)),”Not Found”,”Found”)

If Cell Contains Partial Text Not Case Sensitive

If Range of Cells Contains Text

We can check for the strings in a range of cells. Here is the formula to find If Range of Cells Contains Text. We can use Count If Formula to check the excel if range of cells contains specific text and return Text.

=IF(COUNTIF(A2:A21, “*Region 1d*”)>0,”Range Contais Text”,”Text Not Found in the Given Range”)
  • CountIf function counts the number of cells with given criteria
  • We can use If function to return the required Text
  • Formula displays the Text ‘Range Contains Text” if match found
  • Returns “Text Not Found in the Given Range” if match not found in the specified range

If Cells Contains Text From List

Below formulas returns text If Cells Contains Text from given List. You can use based on your requirement.

VlookUp to Check If Cell Contains Text from a List:
We can use VlookUp function to match the text in the Given list of Cells. And return the corresponding values.

  • Check if a List Contains Text:
    =IF(ISERR(VLOOKUP(F1,A1:B21,2,FALSE)),”False:Not Contains”,”True: Text Found”)
  • Check if a List Contains Text and Return Corresponding Value:
    =VLOOKUP(F1,A1:B21,2,FALSE)
  • Check if a List Contains Partial Text and Return its Value:
    =VLOOKUP(“*”&F1&”*”,A1:B21,2,FALSE)

If Cell Contains Text Then Return a Value

We can return some value if cell contains some string. Here is the the the Excel formula to return a value if a Cell contains Text. You can check a cell if there is given string in the Cell and return some string or value in another column.

If Cell Contains Text Then Return a Value

=IF(ISNUMBER(SEARCH(“How”,A1,1)),”Found”,”Not Found”)

The formula will return true if it found the match, returns False of no match found. can

Excel if cell contains word then assign value

You can replace any word in the following formula to check if cell contains word then assign value.

=IFERROR(IF(SEARCH(“Word”,A2,1)>0,1,0),””)

Excel if cell contains word then assign value
Search function will check for a given word in the required cell and return it’s position. We can use If function to check if the value is greater than 0 and assign a given value (example: 1) in the cell. search function returns #Value if there is no match found in the cell, we can handle this using IFERROR function.

Count If Cell Contains Text

We can check If Cell Contains Text Then COUNT. Here is the Excel formula to Count if a Cell contains Text. You can count the number of cells containing specific text.

=COUNTIF($A$2:$A$7,”*”&D2&”*”)

The formula will Sum the values in Column B if the cells of Column A contains the given text.

If Cell Contains Text Then COUNT

Count If Cell Contains Partial Text

We can count the cells based on partial match criteria. The following Excel formula Counts if a Cell contains Partial Text.

=COUNTIF(A2:A21, “*Region 1*”)
  • We can use the CountIf Function to Count the Cells if they contains given String
  • Wild-card operators helps to make the CountIf to check for the Partial String
  • Put Your Text between two asterisk symbols (*YourText*) to make the criteria to find any where in the given Cell
  • Add Asterisk symbol at end of your text (YourText*) to make the criteria to find your text beginning of given Cell
  • Place Asterisk symbol at beginning of your text (*YourText) to make the criteria to find your text end of given Cell

If Cell contains text from list then return value

Here is the Excel Formula to check if cell contains text from list then return value. We can use COUNTIF and OR function to check the array of values in a Cell and return the given Value. Here is the formula to check the list in range D2:D5 and check in Cell A2 and return value in B2.

=IF(OR(COUNTIF(A2,”*”&$D$2:$D$5&”*”)), “Return Value”, “”)

Excel If cell contains text from list then return value

If Cell Contains Text Then SUM

Following is the Excel formula to Sum if a Cell contains Text. You can total the cell values if there is given string in the Cell. Here is the example to sum the column B values based on the values in another Column.

=SUMIF($A$2:$A$7,”*”&D2&”*”,$B$2:$B$7)

The formula will Sum the values in Column B if the cells of Column A contains the given text.

If Cell Contains Text Then SUM

Sum If Cell Contains Partial Text

Use SumIfs function to Sum the cells based on partial match criteria. The following Excel formula Sums the Values if a Cell contains Partial Text.

=SUMIFS(C2:C21,A2:A21, “*Region 1*”)
  • SUMIFS Function will Sum the Given Sum Range
  • We can specify the Criteria Range, and wild-card expression to check for the Partial text
  • Put Your Text between two asterisk symbols (*YourText*) to Sum the Cells if the criteria to find any where in the given Cell
  • Add Asterisk symbol at end of your text (YourText*) to Sum the Cells if the criteria to find your text beginning of given Cell
  • Place Asterisk symbol at beginning of your text (*YourText) to Sum the Cells if criteria to find your text end of given Cell

VBA to check if Cell Contains Text

Here is the VBA function to find If Cells Contains Text using Excel VBA Macros.

If Cell Contains Partial Text VBA

We can use VBA to check if Cell Contains Text and Return Value. Here is the simple VBA code match the partial text. Excel VBA if Cell contains partial text macros helps you to use in your procedures and functions.

Sub sbCkeckforPartialText()
MsgBox CheckIfCellContainsPartialText(Cells(2, 1), “Region 1”)
End Sub
Function CheckIfCellContainsPartialText(ByVal cell As Range, ByVal strText As String) As Boolean
If InStr(1, cell.Value, strText) > 0 Then CheckIfCellContainsPartialText = True
End Function
  • CheckIfCellContainsPartialText VBA Function returns true if Cell Contains Partial Text
  • inStr Function will return the Match Position in the given string

If Cell Contains Text Then VBA MsgBox

Here is the simple VBA code to display message box if cell contains text. We can use inStr Function to search for the given string. And show the required message to the user.

Sub sbVBAIfCellsContainsText()
If InStr(1, Cells(2, 1), “Region 3”) > 0 Then blnMatch = True
If blnMatch = True Then MsgBox “Cell Contains Text”
End Sub
  • inStr Function will return the Match Position in the given string
  • blnMatch is the Boolean variable becomes True when match string
  • You can display the message to the user if a Range Contains Text

Which function returns true if cell a1 contains text?

You can use the Excel If function and Find function to return TRUE if Cell A1 Contains Text. Here is the formula to return True.

=IF(ISNUMBER(FIND(“YourText”,A1,1)),TRUE,FALSE)

Which function returns true if cell a1 contains text value?

You can use the Excel If function with Find function to return TRUE if a Cell A1 Contains Text Value. Below is the formula to return True based on the text value.

=IF(ISNUMBER(FIND(“YourTextValue”,A1,1)),TRUE,FALSE)

Share This Story, Choose Your Platform!

7 Comments

  1. Meghana
    December 27, 2019 at 1:42 pm — Reply

    Hi Sir,Thank you for the great explanation, covers everything and helps use create formulas if cell contains text values.

    Many thanks! Meghana!!

  2. Max
    December 27, 2019 at 4:44 pm — Reply

    Perfect! Very Simple and Clear explanation. Thanks!!

  3. Mike Song
    August 29, 2022 at 2:45 pm — Reply

    I tried this exact formula and it did not work.

  4. Theresa A Harding
    October 18, 2022 at 9:51 pm — Reply
  5. Marko
    November 3, 2022 at 9:21 pm — Reply

    Hi

    Is possible to sum all WA11?

    (A1) WA11 4

    (A2) AdBlue 1, WA11 223

    (A3) AdBlue 3, WA11 32, shift 4

    … and everything is in one column.

    Thanks you very much for your help.

    Sincerely Marko

  6. Mike
    December 9, 2022 at 9:59 pm — Reply

    Thank you for the help. The formula =OR(COUNTIF(M40,”*”&Vendors&”*”)) will give “TRUE” when some part of M40 contains a vendor from “Vendors” list. But how do I get Excel to tell which vendor it found in the M40 cell?

    • PNRao
      December 18, 2022 at 6:05 am — Reply

      Please describe your question more elaborately.
      Thanks!

© Copyright 2012 – 2020 | Excelx.com | All Rights Reserved

Page load link

Понравилась статья? Поделить с друзьями:
  • Count if cell color in excel
  • Count if and sum if in excel
  • Count function with if excel
  • Count from a range in excel
  • Count frequency of words in word