Lesson 10.4. String and functions

Explanations

Strings inherit the properties of character arrays. The same is true if the string is an argument to a function. The latter can then modify the content of the string (unless the argument is declared with const). However, thanks to the NULL character at the end of the string, it is not necessary to add a second parameter to specify the size of the string.

Example

The ucfirst() function below capitalizes the first character of the string str:

void ucfirst(char str[]) {
  if (str[0]<'a' || str[0]>'z') return;
  str[0] += 'A' - 'a';
}

The string is passed in parameters as an array of characters.

Exercises

Exercise 1

Write a function str_2_upper() that converts the string passed as parameter to uppercase.

For example:

Enter a text: Bonjour !           
In capital letters: BONJOUR !

Exercise 2

Write a function nbSpace() that returns the number of spaces in a string. Here is the expected output of the program:

The text "To be or not to be..." contains 5 space(s).

Exercise 3

Write a function int isCharIn(char s[], char needle) that returns the number of occurrences needle in the string s. Here is the expected output of the program:

The text "To be or not to be..." contains 4 'o' and 2 'e'.

Exercise 4

Write a char palindrome() function that returns:

Enter a word: radar
radar is a palindrome.
Enter a word: pifometer
pifometer is not a palindrome.

Quiz

To pass a string as a parameter in a function ...

Check Bravo! The null character indicates the end of the string and therefore its size Try again...

A character string passed as a parameter in a function ...

char *strcpy(char *s1, const char *s2);
Check Bravo! If a string is passed with the prefix const, it cannot be modified by the function. Try again...

A string passed into a function (without const) can be expanded ...

Check Bravo! The null character must be replaced otherwise it will still indicate the end of the string, even if a second one is added after. Try again...

See also


Last update : 11/28/2022