-
Help with strings
I have a problem trying to call a fuction with the string and the colon (':') as arguments. It is suppose to return then count number of tokens seperated by the colon in the string. The output should be shown in main. Any help is aprreciated. Thanks.
Code:
int countToken(char theString[],':');
int main(void)
{
//local declerations
char theString[] = "abcd0001:groupno:userno:name:/bin/ksh";
int tokenCount;
//statements
tokenCount = countToken(theString,':');
cout << " Number of words in string are: " << tokenCount;
}//main
int countToken (char theString[],':')
{
int count;
while (theString)
{
if (theString[] == ':')
count++;
}//while
return count;
} //countToken
-
>int countToken (char theString[],':')
I don't understand this & don't think it's legal. You need to declare what type your token is, or it you known it's always going to be ':', don't pass it all.
You need to do something like:
Code:
int countToken(char theString[], char token = ':')
{
// Token defaults to ':' if none specified
int count = 0; // Initialise at zero
int len = strlen(theString);
for(int n = 0; n < len; n++) // Loop from character zero to end of string
{
if (theString[n] == token) // Check characters one by one
count++;
}
return count;
}
-
I tried your code...it gave me less errors but i still get one error....It says, "Default argument value redeclared for parameter ' token ' "and shows the error right after the countToken function...???
As well, is there another way i can count the length of a string without using strlen??? Please tell me how if you know. :)
Here is the updated code ..
Code:
int countToken(char theString[],char token = ':');
int main(void)
{
//local declerations
char theString[] = "abcd0001:groupno:userno:name:/bin/ksh";
char token=':';
int count;
count = countToken(theString,token);
cout << " Number of words in string are: " << count;
}//main
int countToken(char theString[], char token = ':')
{
// Token defaults to ':' if none specified
int count = 0; // Initialise at zero
int len = strlen(theString);
for(int n = 0; n < len; n++) // Loop from character zero to end of string
{
if (theString[n] == token) // Check characters one by one
count++;
}
return count;
}