Reputation: 3
I'm probably implementing this code in a terrible way, but i'm currently doing CS50 and trying to search my string for the char '. I searched for other chars such as text [i] == '!'
however when doing text [i] == '''
it doesn't work correctly. Is it possible to make it work in this way?
Here's my terrible code if your interested... i'm trying to find the number of letters, words, and sentences.. it works other than the characters i can't define.
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main (void)
{
string text = get_string("Input text: "); //accept text input
int i;
int length = strlen(text);
int count = 0;
int count2 = 0;
int count3 = 0;
int excludeothers = (length - count);
for (i = 0; i < length; i++)
{
if(text[i] == ' ' || text [i] == '!' || text[i] == '?' || text[i] == '.' || text[i] == ',' || text[i] == '"' || text[i] == ':' || text[i] == ';' || text[i] == '-' || text[i] == ''') //check number of letters
{
count++;
}
}
for (i = 0; i <= length; i++)
{
if((text[i] == ' ' || text[i] == '\0') && (text[i-1] != ' ' || text[i-1] != '\0')) //check number of words
{
count2++;
}
}
for (i = 0; i < length; i++)
{
if((text[i] == '.' || text[i] == '?' || text [i] == '!') && (text[i+1] == ' ' || text[i+1] == '\0')) //check number of sentences
{
count3++;
}
}
printf("%i letters\n", excludeothers); //print letters
printf("%i words\n", count2); //print words
printf("%i sentences\n", count3); //print sentences
}
Upvotes: 0
Views: 187
Reputation: 695
If you want to do it your way, then, yes, you need to escape that character. Take a look at GeeksForGeeks article about escaping characters in general. It will help you knowing which ones can be passed as normal characters and which ones will need a backslash in front of them.
However, if you are considering other options, take a look at strchr()
. It is a builtin function that you can use. Using this will drastically improve and simplify your code. You can take a look at this question discussion for more information. And here is a reference for C documentation on this function.
Upvotes: 0
Reputation: 62797
You need to escape it:
'\''
This means the single quote char. Same way you can have double quote in a string: "\""
Further reading: https://en.wikipedia.org/wiki/Escape_sequences_in_C
Upvotes: 4