Strings - ecology labfaculty.cse.tamu.edu/slupoli/notes/C++/StringsINotes.d… · Web viewC Strings...

26
C Strings C/C++’s versions of Strings There are several types of strings that C++ uses: C Strings (covering now) Strings (newer, simpler) C Strings C String Declaration and Initialization Sets aside an array of elements o each element contains a char (single letter) Do not forget that the initialization of the char array has to be large enough to hold the string and its terminating null, ‘\0’. o terminating null, ‘\0’ ending marker used for string functions described below Assigning values o Must use “ “’s to set if literal o cin >> only reads up to the first white space . Gathering values into C Strings Example 1 char firstname[10], lastname[10]; cin >> firstname >> lastname; // input: Mr. Lupoli cout << lastname << “, “ << firstname; // output: Lupoli, Mr. firstname lastname M r . \ 0 L u p o l i \0 1

Transcript of Strings - ecology labfaculty.cse.tamu.edu/slupoli/notes/C++/StringsINotes.d… · Web viewC Strings...

Page 1: Strings - ecology labfaculty.cse.tamu.edu/slupoli/notes/C++/StringsINotes.d… · Web viewC Strings C/C++’s versions of Strings There are several types of strings that C++ uses:

C StringsC/C++’s versions of StringsThere are several types of strings that C++ uses:

C Strings (covering now) Strings (newer, simpler)

C StringsC String Declaration and Initialization

Sets aside an array of elementso each element contains a char (single letter)

Do not forget that the initialization of the char array has to be large enough to hold the string and its terminating null, ‘\0’.o terminating null, ‘\0’

ending marker used for string functions described below Assigning values

o Must use “ “’s to set if literalo cin >> only reads up to the first white space .

Gathering values into C Strings Example 1char firstname[10], lastname[10];cin >> firstname >> lastname; // input: Mr. Lupolicout << lastname << “, “ << firstname; // output: Lupoli, Mr.

firstname lastnameM r . \0 L u p o l i \0Gathering values into C Strings Example 2

char firstname[10] = “Kristen”;char lastname[10] = “Davis”;cout << lastname << “, “ << firstname; // output: Davis, Kristen

firstname lastnameK r i s t e n \0 D a v i s \0

1

Page 2: Strings - ecology labfaculty.cse.tamu.edu/slupoli/notes/C++/StringsINotes.d… · Web viewC Strings C/C++’s versions of Strings There are several types of strings that C++ uses:

Gathering values into C Strings Example 3char firstname[] = “Mark”; // this would work ONLY when initializing a string

M a r k \0Gathering values into C Strings Example 4

// cin.getline(char str[], int maxcount, char delim);

cout << "Enter a name: " << endl;char wholename[50];cin.getline(wholename, 50, '\n'); // input: “Hello World”//cin.ignore(); // clears and closes stream!! MUST HAVE AFTER!!!

cout << wholename << endl;cout << strlen(wholename) << endl; // What does this do?? Duh??

wholenameH e l l o W o r l d \0

2

Page 3: Strings - ecology labfaculty.cse.tamu.edu/slupoli/notes/C++/StringsINotes.d… · Web viewC Strings C/C++’s versions of Strings There are several types of strings that C++ uses:

Editing & Accessing elements in a char array

HAVE TO DELCARE THE C STRING FIRST!!! The size of the character array is ALREADY fixed when you declare it individual characters inside a character array can be accessed GARBAGE WILL FILL THE REST!!!

Dealing with Garbage#define _CRT_SECURE_NO_WARNINGS // for V.S. 2015#include <iostream>#include <cstring>using namespace std;

void main(){

cout << "Enter a name: " << endl;char wholename[50];cin.getline(wholename, 50, '\n'); // input: “Hello World”

cout << wholename << endl;cout << strlen(wholename) << endl;

cout << "index [7]: " << wholename[7] << endl;cout << "index [5]: " << wholename[5] << endl;cout << "index [30]: " << wholename[30] << endl;

}

Accessing a value inside an C Stringchar fname[8] = “John”;cout << “Character at index 2 is “ << fname[2] << endl; // displays ‘h’

[0] [1] [2] [3] [4] [5] [6] [7]J o h n \0

Editing a value inside a C Stringchar fname[8] = “John”;fname[2] = ‘X’; // editing element number 2, NOTICE NO CHAR!!cout << “Name: “ << fname << endl; // displays “JoXn”

[0] [1] [2] [3] [4] [5] [6] [7]

3

Page 4: Strings - ecology labfaculty.cse.tamu.edu/slupoli/notes/C++/StringsINotes.d… · Web viewC Strings C/C++’s versions of Strings There are several types of strings that C++ uses:

J o X n \0

4

Page 5: Strings - ecology labfaculty.cse.tamu.edu/slupoli/notes/C++/StringsINotes.d… · Web viewC Strings C/C++’s versions of Strings There are several types of strings that C++ uses:

Assignment in C String -> “strcpy” (NO “=”)

use strcpy only if you want to assign ONE STRING TO ANOTHER STRING can use the “=” to initialize a char array syntax

o strcpy (destination, original)

What’s the difference in Assignment?Initialization String to String

char greeting[10] = “Hi all”;// ok to use = for initialization

char username[25];cin >> username;// ok to use cin for initialization

char greeting[10] = “Hi all”;char greeting2[20];

greeting = greeting2;// will not work

Problems with “=”simple data types string data type

#include <cstring>

void main(){

int x = 10;int y = 100;

x = y; // will now equal 100}

#define _CRT_SECURE_NO_WARNINGS // for V.S.2015#include <cstring>

void main(){

char x[10] = "Hi Class";char y[10] = "Welcome";

x = y; // x will now equal Welcome NOT!!}Errors:LValue Required in Function main()x is assigned a value that is never usedy is assigned a value that is never used

5

Page 6: Strings - ecology labfaculty.cse.tamu.edu/slupoli/notes/C++/StringsINotes.d… · Web viewC Strings C/C++’s versions of Strings There are several types of strings that C++ uses:

Different examples using strcpy#define _CRT_SECURE_NO_WARNINGS // for V.S. 2015#include <cstring>using namespace std;

void main( ){

char string1 [20] = “Lupoli”;char string2 [20];strcpy(string1, “Hello World!”); // literal textstrcpy(string2, string1); // predefined variable

}// string1 and string2 now contain “Hello World!”string1H e l l o W o r l d ! \0

string2H e l l o W o r l d ! \0

Strcpy mechanics Strcpy overwrites data, no matter what More than 1 \0 may be in one array!!!

Strcpy ExercisesExample 1

char string1 [20] = “Lupoli”;char string2 [20] = “This crazy class!!”;strcpy(string1, string2);

string1 (before strcpy)

string1 (after strcpy?)

6

Page 7: Strings - ecology labfaculty.cse.tamu.edu/slupoli/notes/C++/StringsINotes.d… · Web viewC Strings C/C++’s versions of Strings There are several types of strings that C++ uses:

Example 2

char string1 [20] = “This crazy class!!”;char string2 [20] = “Lupoli”;strcpy(string1, string2);

string1 (before strcpy)

string1 (after strcpy?)

Which \0 will we stop at??

What is wrong with the code below?

char name[4] = “Ann”;strcpy(name, “David”);

7

Page 8: Strings - ecology labfaculty.cse.tamu.edu/slupoli/notes/C++/StringsINotes.d… · Web viewC Strings C/C++’s versions of Strings There are several types of strings that C++ uses:

testing for the \0 character#include <iostream>using namespace std;

void main(){

char name[10] = "Shaye";

for (int i = 0; name[i] != '\0'; i++){

cout << "DEBUG-> " << name[i] << " at index " << i << endl;

}

cout << " ***************************" << endl;

for (int i = 0; i < 10; i++){

cout << "DEBUG-> " << name[i] << " at index " << i << endl;

}

}

8

Page 9: Strings - ecology labfaculty.cse.tamu.edu/slupoli/notes/C++/StringsINotes.d… · Web viewC Strings C/C++’s versions of Strings There are several types of strings that C++ uses:

Concatenation adds to END of existing char array, where \0 is marked syntax

o strcat (destination, original)

char string1 [22] = “Goodbye”; // drawn belowchar string2 [20] = “, Cruel ”;

string1G o o d b y e \0

strcat(string1, string2);

string1G o o d b y e , _ C r u e l _ \0

strcat(string1, “World!”); // literal string

string1G o o d b y e , C r u e l W o r l d ! \0

Determine what “answer” will look like after the code below:1. char string1 [22] = “Goodbye”; // drawn below2. char string2 [20] = “, Cruel ”; 3. char answer[40];4. strcat(answer, string1);5. strcat(answer, string2);6. strcpy(string1, “Lupoli”);7. strcat(answer, string1);8. cout << answer << endl;

answer

1. create the code for the user to input (cin) a lastname, and a firstname.2. create the code to combine the two strings, “lastname” and “firstname” into one variable Answerb:Revisiting the ASCII Table

9

Page 10: Strings - ecology labfaculty.cse.tamu.edu/slupoli/notes/C++/StringsINotes.d… · Web viewC Strings C/C++’s versions of Strings There are several types of strings that C++ uses:

alphabetical/numerical work just fine but mixing the two proves more interesting

o uses the ASCII table (covered in strings) 0 – 9 A – Z a – z

What value is A, a, Z and z respectfully?

10

Page 11: Strings - ecology labfaculty.cse.tamu.edu/slupoli/notes/C++/StringsINotes.d… · Web viewC Strings C/C++’s versions of Strings There are several types of strings that C++ uses:

Comparison using C Strings (NO “==”) syntax

o value = strcmp(string1, string2); uses an algorithm much like looking for a name in a telephone book

A < Z < a < z in ASCII: 65 < 90 < 97 < 122char string1 [20] = “Apple”;A p p l e \0char string2 [20] = “Wax”;W a x \0

How strings are compared – Coding Example

How Strings are comparedStr1 ? Str2 Delta

#1 L u p o l i ? B r a z e n76 117 112 111 108 105 > 66 114 97 122 101 110 -10L u p o l i ? L u p p o l d76 117 112 111 108 105 < 76 117 112 112 111 108 100 1

Values strcmp( ) returnsreturns when example< 0 string1 alphabetically/ASCII before string2 strcmp(“cat”, “dog”)0 string1 alphabetically/ASCII INDENTICAL string2 strcmp(“dog”, “dog”)> 0 string1 alphabetically/ASCII” after string2 strcmp(“dog”, “cat”)

11

Page 12: Strings - ecology labfaculty.cse.tamu.edu/slupoli/notes/C++/StringsINotes.d… · Web viewC Strings C/C++’s versions of Strings There are several types of strings that C++ uses:

Program to show strcmp functionchar word1[20], word2[20];

for(int i = 0; i < 10; i++){

cout << “Place in word 1:” << endl;cin >> word1;cout << “Place in word 2:” << endl;cin >> word2;cout << “The value returned was: ” << strcmp(word1, word2)) << endl;

if(strcmp(word1, word2) < 0) { cout << “Word 1 < Word 2 “ << endl; }else if (strcmp(word1, word2) > 0){ cout << “Word 1 > Word 2 “ << endl; }else // strcmp(word1, word2) = = 0

{ cout << “Word 1 == Word 2 “ << endl; }cout << ““ << endl;cout << “%%%%%%%%%%%%%%%%%%%%%%% “ << endl;

}

12

Page 13: Strings - ecology labfaculty.cse.tamu.edu/slupoli/notes/C++/StringsINotes.d… · Web viewC Strings C/C++’s versions of Strings There are several types of strings that C++ uses:

string1 = = string2

Problems with “==”simple data types C string data type

#include <iostream>using namespace std;

void main(){

int x = 10;int y = 100;

if( x == y){ cout << “equal!! “ << endl; }else{ cout << “NOT equal!!” << endl; }

// will no equal 100}

#include <iostream>using namespace std;

void main(){

char x[10] = "Hi Class";char y[10] = "Welcome";

if( x == y) // x will compare to y NOT!!{ cout << “equal!! “ << endl; }else{ cout << “NOT equal!!” << endl; }

}Errors:LValue Required in Function main()x is assigned a value that is never usedy is assigned a value that is never used

String comparing exerciseString 1 (x) String 2 (y) comparison Answer (<0, 0, >0)cat dog strcmp(x, y) <0Lupoli Luppold strcmp(x,y)Zach Emily strcmp(x,y)Eric Eric strcmp(x,y)Mandy MANDY strcmp(x,y)

13

Page 14: Strings - ecology labfaculty.cse.tamu.edu/slupoli/notes/C++/StringsINotes.d… · Web viewC Strings C/C++’s versions of Strings There are several types of strings that C++ uses:

Messing with ASCII Table applications the table can tell us a lot about a CHARACTER within a string

Displaying the ASCII value of a charactercout << int('A') << endl; // 65

char letter;cout << "Enter a character, and the ASCII value of that character will be displayed" << endl;cin >> letter;cout << "The ASCII value is: " << int(letter) << endl;

Length finds the length of a string using \0 to stop counting syntax

o strlen(string)

char string1 [15];A p p l e \0cout << strlen(string1) << endl; // displays 5, excludes the ‘\0’

Other tools (functions) for C Strings there are a limited but powerful number of functions please refer to this list http://www.cplusplus.com/reference/cstring/ please look at

o strstro strtoko strchr/strrchr

14

Page 15: Strings - ecology labfaculty.cse.tamu.edu/slupoli/notes/C++/StringsINotes.d… · Web viewC Strings C/C++’s versions of Strings There are several types of strings that C++ uses:

Char Arrays as Parameters C Strings as formal parameters are declared as: Pointer to the first element of the string Changes to the string inside the function affect the actual string DO NOT NEED ‘&’

Char Arrays as ParametersCall Function Parameter

void main(){char name[20] = “Lupoli”;

display_array(name);…

void display_array ( char x[20] ){// will display as separate lettersfor(int i = 0; i < strlen(x); i++)

{ cout << x[i]; }cout << endl;}

Messing with getline the examples below explain a little of the syntax in a getline command

Getline examples#include <iostream>#include <cstring>using namespace std;

void main(){

char fname[20];char lname[20];char wholename[50];

cout << "Enter a first and last name: " << endl;

cin.getline(fname, 5, '\n');

cout << fname << endl;cout << strlen(fname) << endl;

#include <iostream>#include <cstring>using namespace std;

void main(){

char fname[20];char lname[20];char wholename[50];

cout << "Enter a first and last name: " << endl;

cin.getline(fname, 20, '\n');

cout << fname << endl;cout << strlen(fname) << endl;

15

Page 16: Strings - ecology labfaculty.cse.tamu.edu/slupoli/notes/C++/StringsINotes.d… · Web viewC Strings C/C++’s versions of Strings There are several types of strings that C++ uses:

Breaking down a String you can look at individual chars inside a string need to include <ctype.h> use the char functions to determine what is inside that string

o isalphao isdigito ispunct

o isspaceo islowero isupper

string line = “Goodbye, Cruel World”;

G o o d b y e , C r u e l W o r l d ! \0√ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √Total = 17

isalpha exampleint count = 0;for(int i = 0; i < strlen(line); i++) // counts # of letters in the string OR line.size(){

if(isalpha(line[i] )) { count++; }}cout <<count;

isdigit exampleint count = 0;for(int i = 0; i < strlen(line); i++) // counts # of numbers in the string{

if(isdigit(line[i] )) { count++; }}cout <<count;

Ispunct exampleint count = 0;for(int i = 0; i < strlen(line) ;i++) // counts # of punctuation marks in the string{

if(ispunct(line[i] )) { count++; }}cout <<count;

16

Page 17: Strings - ecology labfaculty.cse.tamu.edu/slupoli/notes/C++/StringsINotes.d… · Web viewC Strings C/C++’s versions of Strings There are several types of strings that C++ uses:

Count “s” exampleint count = 0;for(int i = 0; i < strlen(line) ;i++) // counts # of ‘s’ in the string{

if( line[i] == ‘s’ ) { count++; }}cout <<count;

Answer SectionCombining First Name and Last Name

#include <iostream>#include <cstring>using namespace std;

void main(){

char fname[20];char lname[20];char wholename[50];

cout << "Enter a first and last name: " << endl;

cin >> fname;cin >> lname;strcpy(wholename, fname);strcat(wholename, " ");strcat(wholename, lname);

cout << wholename << endl;cout << strlen(wholename) << endl;

cout << "index [7]: " << wholename[7] << endl;

cout << "index [5]: " << wholename[5] << endl;

cout << "index [30]: " << wholename[30] << endl;}

#include <iostream>#include <cstring>using namespace std;

void main(){

char fname[20];char lname[20];char wholename[50];

cout << "Enter a first and last name: " << endl;

cin.getline(fname, 20, '\n');cin.getline(lname, 20, '\n');

strcpy(wholename, fname);strcat(wholename, " ");strcat(wholename, lname);

cout << wholename << endl;cout << strlen(wholename) << endl;

cout << "index [7]: " << wholename[7] << endl;

cout << "index [5]: " << wholename[5] << endl;

cout << "index [30]: " << wholename[30] << endl;}

17