: class Programming 2 2015-2016
Index 1 characters in C 2 Input / output 3 Conversion between arrays of characters and strings 4 Comparison with arrays of characters 5
characters in C characters in C have a constant (fixed) length: char cad[10]; It is also possible to declare them with a dynamic length in different ways: int tamcad; cin >> tamcad; char cad[tamcad]; // Not recommended by standard char *cad = (char *)malloc(tamcad*sizeof(char)); // C char *cad = new char[tamcad]; // C++ However, once declared they cannot change their size.
with C character arrays from C++ cout : like other simple variables (int, float,... ) Beware: the character array must end with \0 cin : almost like other variables cin ignore blanks before the character array... It stops reading when the first space, tab or \n is read afterwards. Problem: what happens if the character array contains blanks? It doesn t limit the number of characters to be read. BIG PROBLEM: what happens if the characters don t fit into the array?
getline Using getline, arrays can be read with blanks and their size can be controlled. cin.getline(cadena,tam) It reads as maximum TAM-1 characters or until the end of the line The character \n at the end of the line is read but not stored into the array. It adds the character \0 at the end of the contents that were read (that s why it only reads TAM-1 characters)... but if the user introduces more characters than the maximum, they remain in the buffer and the next reading fails.
Problems mixing» with getline int num; cout << "Num= "; cin >> num; char cadena[1000]; cout << "Write something: " ; cin.getline(cadena,1000); cout << "I read: " << cadena << endl; Num= 10 Write something: I read: Why? Using >>, 10 is read, but it stops reading at the first character which is not a number \n getline finds a \n in the buffer, therefore an empty array of characters is read. Solution: cin >> num; cin.get(); // Reads \n
Functions in string.h (1/2) strlen returns the length of an array of characters. char cad[] = "bye!"; cout << strlen(cad) << endl; // Prints 4 strcmp compares two arrays in lexicographical order, returning a negative value if a < b, zero if a == b, or positive if a > b. char cad[] = "adios"; char otra[] = "adeu"; cout << strcmp(cad,otra) << strcmp(otra,cad) << strcmp(cad,cad) << endl; // Prints 1-1 0 strcpy copies an array into another (beware, segmentation fault if it does not fit) char cad[10]; strcpy(cad,"hola"); // fits, there are 4 + \0 = 5 chars
Functions in string.h (2/2) The functions strncmp, strncpy compare or copy only the first n characters. Example: char cad[tcad]; strncpy(cad,"hola, mundo",4); // It only copies "hola" cad[4] = \0 ; // It does not automatically copy \0 To convert an array of characters into an integer or a float, you can use atoi, or atof. #include <cstdlib> // Important! char cad[]="100"; int n=atoi(cad); // n is 100 char cad2[]="10.5"; float f=atof(cad2); // f is 10.5
Strings in C++: class can be used in C++ (although arrays of characters can also be used) Passing strings as function parameters (by value or reference) is similar to any simple type (int, float,... ), length is variable (there is no maximum limit), and it can grow It doesn t end with \0
Constant: const string cadena="hola"; Variable: string cadena; with initialization: string cadena = "hola";
with strings cout : like simple types (int, float,... ) cin : almost like the arrays of characters Blanks before the string are ignored, and reading stops when the first blank after the data is found. String containing blanks can also be read: getline(cin,cadena) (warning, the syntax is different to that of arrays of characters) The number of characters to be read is not constrained Warning: Calling >> and afterwards getline produces the same problems seen with arrays of characters You can read until a given character using: getline(cin,cadena,, )
string methods (1/2) A string is a class, therefore methods are called using a dot after the variable name. Example: unsigned int tam=s.length(); // s is a string String length: unsigned int length(); Substring search: unsigned int find (const string str, unsigned int pos=0); // If not found, it returns the string::npos constant Substring replacement: string& replace (unsigned int pos, unsigned int tam, const string str); Remove a substring string& erase (unsigned int pos=0, unsigned int tam=npos);
string methods (2/2) string a="hay una taza en esta cocina con tazas"; string b="taza"; // Length of a unsigned int tam = a.length(); // Searching for the first word taza unsigned int encontrado=a.find(b); if (encontrado!=string::npos) cout << "primera taza en: " << encontrado << endl; else cout << "palabra taza no encontrada"; // Searching for the second word taza encontrado=a.find("taza",encontrado+b.length()); if (encontrado!=string::npos) cout << "segunda taza en: " << encontrado << endl; else cout << "palabra taza no encontrada"; // The first taza is replaced by botella a.replace(a.find(b),b.length(),"botella"); cout << a << endl;
string operations Comparisons: ==,!=, >, <, >= and <= String assignment: using operator =, like with simple types. String concatenation: using operator + s1 = "hola" ; s2 = "mundo"; s = s1 + ", " + s2; cout << s << endl ; // prints hola, mundo Components can be accessed like in arrays of characteres: only if the string contains something there. s = "hola" ; car = s[3]; s[0] = H ; cout << s << ":" << car << endl ; // prints Hola:a // Loop example for (unsigned int i=0; i<s.length(); i++) s[i]= f ;
Conversion between arrays of characters and strings array of characters to string: using the assignment operator (=) char cad[] = "hola"; string s ; s = cad ; s = s + ", mundo"; string to array of characters : using c_str char cad[tcad]; string s = "mundo"; // Warning: cad must be long enough strcpy(cad, s.c_str());
Conversion between string and integer Integer to string #include <sstream> int n=100; stringstream ss; ss << n; // More data can be concatenated, e.g.: // ss << "The number is: " << n << endl; string number=ss.str(); string to integer string number="100"; int n=atoi(number.c_str());
Tokenize strings You can extract fields from a string using the class stringstream. For example: #include <sstream> int main() { stringstream ss("hola mundo cruel 1 32 2"); string s; while (ss>>s) { cout << "s: " << s << endl; } }
Comparison between arrays of characters and strings arrays of characters string char cad[tam]; string s; char cad[]="hola"; string s="hola"; strlen(cad) s.length() cin.getline(cad,tam); getline(cin,s); if (!strcmp(c1,c2)){..} if (s1 == s2){..} strcpy(c1,c2); s1 = s2; strcat(c1,c2); s1 = s1 + s2; strcpy(cad,s.c_str()); s = cad; They end with \0 They DON T end with \0 Fixed length Variable length (it can grow) Variable used size Used size = reserved size They can be used in binary files They CAN T be used in binary files
(1/4) Exercise 1 Design a function called SubCadena to extract a substring of length n, starting from the position p of other string. Both the argument and the return variable must be strings. SubCadena("hoooola", 2, 5) "la" Exercise 2 Design a function called BorraCaracterDeCadena. Given a string and a character, it must delete all the occurrences of the character in the string. "hola, mundo" o "hla, mund"
(2/4) Exercise 3 Design a function BuscarSubCadena to find the first occurrence of the substring a into the string b, returning its position, or 1 if it is not found. Variables a and b must be strings. BuscarSubCadena("oool", "hoooola") 2 Extensions: 1 Extend the function to allow another parameter, the occurrence number (being 1, it would be like the original function, searching for the first occurrence) 2 Implement a similar function returning the total number of occurrences of a in b.
(3/4) Exercise 4 Design a function called Codifica for encrypting a string by summing a constant value c to the ASCII code of each character. It must be considered that the result should be a letter. For instance, if n = 3, a is coded as d, b as e,..., x as a, y as b, and z as c. The function must allow uppercase and lowercase letters, and the non-letter characters shouldn t be encrypted. Codifica("hola, mundo", 3) "krod, pxqgr"
(4/4) Exercise 5 Design a function EsPalindromo to return true if the string passed as parameter is palindromic. EsPalindromo("hola,aloh") true EsPalindromo("hola, aloh") false Exercise 6 Design a function called CreaPalindromo for adding to a given string the same one but reversed, in such a way that the output string will be palindromic. "hola, mundo" "hola, mundoodnum,aloh" This can be done in two ways: string CreaPalindromo(string); void CreaPalindromo(string &);