Converting a Lowercase Letter Character to Uppercase (Or Vice Versa)

Similar documents
Characters, c-strings, and the string Class. CS 1: Problem Solving & Program Design Using C++

Chapter 10: Characters, C- Strings, and More About the string Class

Chapter 10: Character Testing. From Program Character Case Conversion 8/23/2014. Character Testing. Character Case Conversion

Chapter 10: Characters, C- Strings, and More About the string Class Character Testing

Scientific Programming in C V. Strings

Chapter 10 Characters, Strings, and the string class

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

Strings and Library Functions

Fundamentals of Programming. Lecture 11: C Characters and Strings

Chapter 8 - Characters and Strings

C: How to Program. Week /May/28

System Design and Programming II

Introduction to Algorithms and Data Structures. Lecture 6 - Stringing Along - Character and String Manipulation

today cs3157-fall2002-sklar-lect05 1

Characters and Strings

C mini reference. 5 Binary numbers 12

LECTURE 15. String I/O and cstring library

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

CS3157: Advanced Programming. Outline

Chapter 8: Character & String. In this chapter, you ll learn about;

String Class in C++ When the above code is compiled and executed, it produces result something as follows: cin and strings

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University

Topic 3. Big C++ by Cay Horstmann Copyright 2018 by John Wiley & Sons. All rights reserved

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Computer Science XII Important Concepts for CBSE Examination Questions

Haskell Programs. Haskell Fundamentals. What are Types? Some Very Basic Types. Types are very important in Haskell:

C Libraries. Bart Childs Complementary to the text(s)

C Style Strings. Lecture 11 COP 3014 Spring March 19, 2018

Introduction to C/C++ Lecture 5 - String & its Manipulation

Computer Programming

Module 4 Arrays, Strings, and Pointers

ch = argv[i][++j]; /* why does ++j but j++ does not? */

Approximately a Test II CPSC 206

Chapter 8 C Characters and Strings

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Strings. Arrays of characters. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY

Programming in C. Session 7. Seema Sirpal Delhi University Computer Centre

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

Topic 2. Big C++ by Cay Horstmann Copyright 2018 by John Wiley & Sons. All rights reserved

Contents. Preface. Introduction. Introduction to C Programming

Strings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break

Structured programming

CS 261 Fall Mike Lam, Professor. Structs and I/O

Outline. Computer Programming. Structure of a function. Functions. Function prototype. Structure of a function. Functions

Chapter 5. Section 5.4 The Common String Library Functions. CS 50 Hathairat Rattanasook

C strings. (Reek, Ch. 9) 1 CS 3090: Safety Critical Programming in C

LECTURE 02 INTRODUCTION TO C++

Strings. Steven R. Bagley

3. Functions. Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs.

A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called.

Grade Distribution. Exam 1 Exam 2. Exams 1 & 2. # of Students. Total: 17. Total: 17. Total: 17

C++ for Java Programmers

CS 31 Review Sheet. Tau Beta Pi - Boelter Basics 2. 2 Working with Decimals 2. 4 Operators 3. 6 Constants 3.

Tokens, Expressions and Control Structures


SWEN-250 Personal SE. Introduction to C

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

Chapter 7. Basic Types

Strings and Stream I/O

Object Oriented Programming COP3330 / CGS5409

ONE DIMENSIONAL ARRAYS

ECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

CISC 1110 (CIS 1.5) Introduc2on to Programming Using C++

Chapter 7 C Pointers

Iosif Ignat, Marius Joldoș Laboratory Guide 9. Character strings CHARACTER STRINGS

Working with Sequences: Section 8.1 and 8.2. Bonita Sharif

Computer Programming: Skills & Concepts (CP) Strings

AIR FORCE SCHOOL,BAMRAULI COMPUTER SCIENCE (083) CLASS XI Split up Syllabus (Session ) Contents

CSCI 6610: Review. Chapter 7: Numbers Chapter 8: Characters Chapter 11 Pointers

String Processing CS 1111 Introduction to Programming Fall 2018

Fundamentals of Computer Programming Using C

Computers Programming Course 11. Iulian Năstac

C Programming. Unit 9. Manipulating Strings File Processing.

Memory, Arrays & Pointers

Strings in C++ Dr. Ferdin Joe John Joseph Kamnoetvidya Science Academy

Introduction to String Manipulation

Programming in C++ 4. The lexical basis of C++

6.096 Introduction to C++ January (IAP) 2009

Appendix A Developing a C Program on the UNIX system

LESSON 4. The DATA TYPE char

13 4 Understanding Character Strings

String constants. /* Demo: string constant */ #include <stdio.h> int main() {

Announcements. Strings and Pointers. Strings. Initializing Strings. Character I/O. Lab 4. Quiz. July 18, Special character arrays

Exercise 1.1 Hello world

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

CCE1111 Programming for Engineers [C Programming Language]

CS102: Variables and Expressions

Introduction to string

Intermediate Programming, Spring 2017*

by Pearson Education, Inc. All Rights Reserved.

Arrays array array length fixed array fixed length array fixed size array Array elements and subscripting

OBJECTIVE QUESTIONS: Choose the correct alternative:

The C++ Language. Arizona State University 1

Object-Oriented Programming

Chapter 9 Strings. With this array declaration: char s[10];

BITG 1113: Array (Part 2) LECTURE 9

Chapter 8: More About Strings. COSC 1436, Summer 2018 Dr. Zhang 7/10/2018

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

Transcription:

Looping Forward Through the Characters of a C String A lot of C string algorithms require looping forward through all of the characters of the string. We can use a for loop to do that. The first character of the string will be at array index 0. The most efficient way to detect that we ve reached the end of the string is to check for the null character: char str[80] = "Some text"; for (int i = 0; str[i]!= '\0'; i++) // Do something with the character str[i]. Looping Backward Through the Characters of a C String Some C string algorithms require looping backward through all of the characters of the string instead. Once again, we can use a for loop to do that. The key here is to recognize that the last non-null character of the string is always located at array index (length of the string 1). For example, the C string "cat" has a length of 3, so its last non-null character is located at array index 2: 0 1 2 3 str c a t \0 We can use the library function strlen() to find the length of a C string, and then loop backward from the last non-null character of the string to the first character: char str[80] = "Some text"; for (int i = strlen(str) - 1; i >= 0; i--) // Do something with the character str[i]. Converting a Lowercase Letter Character to Uppercase (Or Vice Versa) The library function toupper() from the header file <cctype> can be used to convert a lowercase letter character to uppercase, like so: ch = toupper(ch); If the character variable ch contains a lowercase letter, the uppercase equivalent of that letter will be returned by the function. Otherwise, the value of the character will be returned unchanged. In both cases, we can then assign the return value from the function back to the character variable. Of course, this works identically with the individual elements of an array of char:

A similar function called tolower() can be used to convert uppercase letters to lowercase. Determining the Type of a Character The header file <cctype> also contains several functions that allow you to test whether or not a character belongs to a particular type: a digit, an alphabetic character, a lowercase letter, etc. These functions are part of the older C library and predate the bool data type added in C++, so they take a character as their argument and return an integer either 0 (meaning false), or not 0 (meaning true). Note that not 0 is not the same thing as 1. Any non-zero value is evaluated as true by C and C++, and the exact value the function returns is compiler-dependent. It s important to take that fact into account when you code a test: // Wrong way to code the test - there is no guarantee that // the isdigit() function will return 1 if str[i] is a digit. if (isdigit(str[i]) == 1) // The character str[i] may or may not be a numeric digit. // Correct way to code the test - C++ will treat any non-zero // return value as true and zero as false. if (isdigit(str[i])) // The character str[i] is a numeric digit. The is functions available in the library include: isalpha() is the character an alphabetic character (i.e., a letter)? isalnum() is the character an alphanumeric character (i.e., a letter or a numeric digit)? isdigit() is the character a numeric digit? islower() is the character a lowercase letter? isupper() is the character an uppercase letter? ispunct() is the character a punctuation character? (Read the documentation to see what qualifies.) isspace() is the character a white-space character (space, tab, newline, carriage return, etc.)? Comparing One Character of a String Another common thing you might want to do is compare a character of a C string to another character. For example, you might want to answer the question, Does this string contain this particular character? or you might want to count how many times a particular character occurs in a string.

Since a C string is an array of char and the char data type can be compared using the standard relational operators, this is straightforward to code: if (str[i] == ch) // The character str[i] is equal to the character ch. Passing C Strings to and Returning C Strings from Functions If you look at online documentation for most of the C string functions, you might see some data types in the prototypes that you may not recognize yet. For example, here is the prototype for the strcpy() function: char* strcpy(char* destination, const char* source); If you were able to look at the actual code for the strcpy() function, it might look something like this: char* strcpy(char* destination, const char* source) int i; for (i = 0; source[i]!= '\0'; i++) destination[i] = source[i]; destination[i] = '\0'; return destination; The return data type and the data type of the parameter destination are char* (pointer to a char). The data type of the parameter source is const char* (pointer to a char constant). Every variable in C and C++ has an address, a number that identifies its location in the computer s memory. A pointer is a special type of variable that can hold the address of another variable. The pointer can then be used to access the value of the variable to which it points. Normally, when you pass a variable to a function what gets passed is a copy of the variable s value. The value is copied into a local variable that you declared as a function parameter. Arrays in C and C++ work differently. Making a copy of an entire array every time you pass it to function could potentially be expensive in terms of both time and memory. Instead, the designers of C chose to pass a copy of the address of the array (technically, the address of the first element of the array) to the function. That address is copied into a local pointer variable declared as a function parameter. The pointer can then be used to access the values stored in the array in the calling function. In the prototype above, source and destination are pointers to the first element of arrays of char. For the function to work correctly, the pointer destination must point to an array of char

that is a C string (i.e., that contains a null character), while destination just needs to point to an array of char. The strcpy() function can access the contents of both arrays, but all that actually gets copied to the function are the addresses of the arrays, which are only four or eight bytes each. A potential downside of passing the address of an array to a function is that the function will be able to change the contents of the array in the calling routine. While we want strcpy() to be able to change the contents of the array destination in the calling function, we don t want it to be able to accidentally change the contents of source. The pointer source might be pointing to a C string literal, for example. Changing that could have unforeseen effects on our program. That s where the const keyword comes in. The const keyword that is part of the declaration of source means that pointer can t be used to change the values stored in the array to which it points. They can be read or copied, but not altered. If you try to assign a new value to source[i], you will get a syntax error. You ll see the data type const char* used for any C string parameter that could potentially be a C string literal. Note that the code in the function body treats source and destination as if they were arrays (which in fact they are). In C/C++, array elements are always accessed by their address. Any pointer variable may be subscripted like an array name, and an array name is automatically converted into a pointer to the first element of the array when you subscript it. You could rewrite the strcpy() function to declare the data types using array syntax rather than pointer syntax: char[] strcpy(char destination[], const char source[]) int i; for (i = 0; source[i]!= '\0'; i++) destination[i] = source[i]; destination[i] = '\0'; return destination; That changes nothing. The variables source and destination are still pointers to the first element of arrays of char, so most C/C++ programmers will use the pointer syntax. The strcpy() function also returns the pointer destination. That pointer points to the first element of the copied string. A lot of the C string functions do this. When you call the strcpy() function, you might ignore the return value. For example: char name[21] = "John Smith"; strcpy(name, "Amy Jones"); // Initialize name to "John Smith". // name now contains "Amy Jones". However, we can use the value returned by a C string function like strcpy() or strcat() to perform nested function calls:

char firstname[] = "Amy"; char lastname[] = "Amy"; char fullname[21]; strcat(strcat(strcpy(fullname, lastname), ", "), firstname); The final statement in the code above is equivalent to doing these three separate function calls: strcpy(fullname, lastname); strcat(fullname, ", "); strcat(fullname, firstname); Nesting function calls like the example above doesn t actually make your code more efficient you re still performing three function calls, just all in one line of code. It is a bit less typing, but it s also a lot less readable and harder to understand. The size_t Data Type Another new data type that you may encounter in reading the documentation for the C and C++ string functions is size_t. For example, here is the prototype for the strlen() function: size_t strlen(const char* str); And here is the prototype for the length() method of the C++ string class: size_t length() const noexcept; The name size_t essentially means size type, and you will typically see this data type used to specify the size or length of things like the length of a C string returned by the strlen() function, for example. This is not one of the built-in data types of C/C++. Instead, it was defined in several header files using the typedef command: typedef unsigned int size_t; The statement above defines a new data type called size_t as an unsigned int. It s basically just creating a shorter alias for the unsigned int data type. An unsigned int is an integer that can be 0 or greater than 0 but cannot be negative. If you think about it a bit, it makes sense to use this data type for something like the length of a C string. You can have a C string that is length 0 (nothing but a null character), but how could you possibly have a string with a negative length? For the most part, you can treat a size_t variable as if it were an integer without any issues. One problem that does come up however is that the C++ compiler will give you a warning if you compare an integer to an unsigned integer:

string str = "something something something"; for (int i = 0; i < str.length(); i++) Here, i is data type int while the return value from the length() method is data type size_t (an unsigned int). The compiler will flag this comparison with a warning. There are two ways to fix this kind of warning. 1. We can type cast the return value of the length() method to an integer. string str = "something something something"; for (int i = 0; i < (int) str.length(); i++) 2. We can declare i as data type size_t or unsigned int instead of data type int. string str = "something something something"; for (size_t i = 0; i < str.length(); i++)