C/C++ library function (tolower/toupper) implements case conversion of letters
This article will introduce the library function to implement the case conversion of letters, commonly used in the type. H (c ++ is cctype) library file under the definition of function methods. First let’s look at the prototype implementation of the tolower/toupper function under C:
int tolower(int c)
{
if ((c >= 'A') && (c <= 'Z'))
return c + ('a' - 'A');
return c;
}
int toupper(int c)
{
if ((c >= 'a') && (c <= 'z'))
return c + ('A' - 'a');
return c;
}
And I’m going to do that with two little demos.
C implementation:
#include<string.h> //strlen
#include<stdio.h> //printf
#include<ctype.h> //tolower
int main()
{
int i;
char string[] = "THIS IS A STRING";
printf("%s\n", string);
for (i = 0; i < strlen(string); i++)
{
string[i] = tolower(string[i]);
}
printf("%s\n", string);
printf("\n");
}
Save as xxX. c file, execute: GCC-O XXX xxX. c generate execute file XXX. Operation:./ XXX
above is the implementation of C. Similarly, the implementation under C++ is as follows:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string str= "THIS IS A STRING";
for (int i=0; i <str.size(); i++)
str[i] = tolower(str[i]);
cout<<str<<endl;
return 0;
}
Save as xxx. CPP, execute g++ xxx. CPP to generate the execution file a.ut, execute a.ut, and the effect is as follows:
The demo above
implements the upper case tolower case conversion, again, the lower case toupper case conversion is the same, just replace tolower with toupper.
Read More:
- Differences between length() size() and C strlen() of C + + string member functions
- error: a label can only be part of a statement and a declaration is not a statement (How to Fix)
- The language of C__ FILE__ 、__ LINE__ And line
- Conversion from hexadecimal to decimal
- [Warning] incompatible implicit declaration of built-in function ‘strcat’
- pthread_ Introduction and application of join function
- Error in comparing the size function of STL with negative number
- Waitpid call return error prompt: no child processes problem
- Python switch / case statement implementation method
- In Java, int is converted to string, and zero is added before the number of bits is insufficient
- The function and usage of argc and argv in C language
- Implementation of Python switch / case statements
- fatal error LNK2019[UNK]fatalerror LNK1120
- Errno in Linux Programming
- Error c2137 of C language: empty character constant (Fixed)
- C language write() function analysis: write failed bad address
- error: invalid use of non-static member function
- error C2057: expected constant expression (Can the size of an array in C language be defined when the program is running?)
- Finding the longest connection path of a string
- Gcc compiler warning solution: “extra tokens at end of ifndef directive” Tags: GCC, warning