1

I'm just starting to code and I need help figuring out why this loop counts spaces within a string.

To my understanding, this code should tell the computer to not count a space "/0" and increase count if the loop goes through the string and it's any other character.

int main(void)
{

    string t = get_string("Copy & Past Text\n");
    int lettercount = 0;

   for (int i = 0; t[i] != '\0'; i++)
    {
          lettercount++;
        
    }

    printf("%i", lettercount);

    printf("/n");
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

5 Answers5

3

\0 represents the null character, not a space. It is found at the end of strings to indicate their end. To only check for spaces, add a conditional statement inside the loop.

int main(void)
{
    string t = get_string("Copy & Past Text\n");
    int lettercount = 0;

    for (int i = 0; t[i] != '\0'; i++)
    {
        if (t[i] != ' ')
            lettercount++;
    }

    printf("%i", lettercount);

    printf("\n");
}
AJ_
  • 1,455
  • 8
  • 10
  • 1
    `for (int i = 0; i < strlen(string); i++)` is ok but `for (int i = 0, n = strlen(string); i < n; i++)` as doesn't need to constantly check how long the string each time. – Manav Dubey Jul 09 '20 at 16:10
  • Yes, I completely agree with both of you. I didn't really think twice about it because I wasn't sure what the definition of `string` looked like, `strlen()` is just used a placeholder function to communicate the idea. I've adjusted my code to reflect that the length shouldn't be calculated repeatedly. @ikegami, In terms of why I changed it, please see the second paragraph of my answer. – AJ_ Jul 09 '20 at 16:17
  • Yea my bad, completely misinterpreted the original for loop's condition. My answer has been simplified to just add the condition. – AJ_ Jul 09 '20 at 16:39
1

Space is considered a character, your code goes through the string (an array of characters) and counts the characters until it reaches the string-terminating character which is '\0'.

Edit: set an if condition in the loop if(t[i] != ' ') and you wouldn't count the spaces anymore.

Nima
  • 381
  • 2
  • 8
1

You misunderstand the nature of C strings.

A string is an array of characters with a low value ( '\0') marking the end of the string. Within the string some of the characters could be spaces (' ' or x20).

So the " t[i] != '\0' " condition marks the end of the loop.

A simple change:

if ( t[i] != ' ') {
    lettercount++;
}

Will get your program working.

James Anderson
  • 27,109
  • 7
  • 50
  • 78
1

This for loop

for (int i = 0; t[i] != '\0'; i++)

iterates until the current character is the terminating zero character '\0' that is a null character. So the character is not counted.

In C there is the standard function isalpha declared in the header <ctype.h> that determines whether a character represents a letter.

Pay attention to that the user can for example enter punctuation symbols in a string. Or he can use the tab character '\t' instead of the space character ' '. For example his input can look like "~!@#$%^&" where there is no any letter.

So it would be more correctly to write the loop the following way

size_t lettercount = 0;

for ( string s = t; *s; ++s )
{
    if ( isalpha( ( unsigned char )*s ) ) ++lettercount;
}

printf("%zu\n", lettercount );

This statement

printf("/n");

shall be removed. I think instead you mean

printf("\n");

that is you want to output the new line character '\n'. But this character can be inserted in the previous call of printf as I showed above

printf("%zu\n", lettercount );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

A null-terminator is the last leading element in a character array consisting of a string literal (e.g. Hello there!\0). It terminates a loop and prevent further continuation to read the next element.

And remember, a null-terminator isn't a space character. Both could be represented in the following way:

\0 - null terminator | ' ' - a space

If you want to count the letters except the space, try this:

#include <stdio.h>

#define MAX_LENGTH 100

int main(void) {
    char string[MAX_LENGTH];
    int letters = 0;

    printf("Enter a string: ");
    fgets(string, MAX_LENGTH, stdin);

    // string[i] in the For loop is equivalent to string[i] != '\0'
    // or, go until a null-terminator occurs
    for (int i = 0; string[i]; i++)
        // if the current iterated char is not a space, then count it
        if (string[i] != ' ')
            letters++;

    // the fgets() reads a newline too (enter key)
    letters -= 1;

    printf("Total letters without space: %d\n", letters);

    return 0;
}

You'll get something like:

Enter a string: Hello world, how are you today?
Total letters without space: 26

If a string literal has no any null-terminator, then it can't be stopped from getting read unless the maximum number of elements are manually given to be read till by the programmer.

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34