If my_array[50]
has randomly uppercase letters inside, is there any way to find the find them and switch them to lowercase letters? I am really looking for an implementation-independent method because it is going to be cross platform. The code will be used on other languages too.
Asked
Active
Viewed 89 times
-2

Eric Postpischil
- 195,579
- 13
- 168
- 312

k2iron
- 19
- 1
- 2
-
"If my_array[50] as randomly uppercase letters inside" please show the code for that. Define the array and fill it with sample data. Please explain "find the element id ". Do you mean search for the index of the character with certain attributes? I understand that all characters are upper case, so what attribute would that be? Cross platform and regex do not seem realted, what do you mean? All in all, I really do not get what you are asking. – Yunnosch Jul 12 '19 at 23:33
-
What can the string contain to begin with? Only ASCII letters? Any Unicode at all, encoded as UTF-8? Something else? – Ry- Jul 12 '19 at 23:41
-
Basically just numbers letters and simple characters, nothing to crazy going UTF-8 – k2iron Jul 12 '19 at 23:41
-
A simple loop over elements of the array, and use of `tolower()` function will work. If you want it to work with other (non-programming) languages, look up use of locales. – Peter Jul 13 '19 at 02:05
1 Answers
4
C provides a tolower
function that converts uppercase letters to lowercase letters and leaves other characters unchanged. It is affected by the current locale (it will use different alphabets depending on the locale you set with the setlocale
function). It should be used with unsigned char
characters.
#include <ctype.h>
#include <stdlib.h>
/* Given length characters starting at p,
convert uppercase letters to lowercase.
*/
void ToLower(size_t length, unsigned char *p)
{
for (size_t i = 0; i < length; ++i)
p[i] = tolower(p[i]);
}
(For “wide characters,” the function towctrans
provides a similar operation. It is more complicated to use.)

Eric Postpischil
- 195,579
- 13
- 168
- 312
-
I think this catches all characters, it doesn't actually check if its from range A - Z. – k2iron Jul 12 '19 at 23:48
-
@k2iron If it's not a letter, it returns the original value. There's no need to add a check in the caller. – Barmar Jul 12 '19 at 23:50
-
`tolower()` doesn't only work with `unsigned char`. It's argument and return value is of type `int`. – Peter Jul 13 '19 at 02:08
-
1@Peter: The fact that the **type** of the parameter is `int` does not mean the behavior is defined for any **value** of type `int`. Per C 2018 7.4 1: “In all cases the argument is an `int`, the value of which shall be representable as an `unsigned char` or shall equal the value of the macro `EOF`. If the argument has any other value, the behavior is undefined.” If you pass `tolower` a negative value other than `EOF`, the behavior is not defined by the C standard. – Eric Postpischil Jul 13 '19 at 02:10