Monday, October 26, 2015

Rad sa stringovima u C++ programskom jeziku


Jedan od najčešći komunikacija računara sa korisnikom su tekstualni stringovi. Gotovo je nemoguće i zamisliti neki program bez teksta. Mogućnost da kombinujete, rastavljate i analizirate stringove je danas nešto što se podrazumeva kao abeceda programiranja. Bez obzira šta vi radite sa stringovima, računar njih pamti i radi s njima kao da su to brojevi. Zato tekstualni podaci jednostavno u svakom bajtu koriste specijalan kod koji odgovara konkretnom znaku, i taj kod zovemo ASCII kod. Prevođenje stringova u brojeve i obratno se vrši iza scene, pa vi nemate taj osećaj ali tako se prevode najmanje dvaput kad unosite tekst sa tastature i kad ga prikazujete na ekranu. Inače u C++ programskom jeziku string je zapravo niz, koji se sastoji od elemenata tipa char i završava se null karakterom ( \0 ).



( C++ , string data type )


Pogledajte ovu liniju koda:

char myString[] = {'M','a','n','u','e','l','','R','a','d','o','v','a','n','o','v','i','c','\0' };

Ovako pisanje koda kad je tekst u pitanju je zamorno i kompleksno. Iako karakter po karakter, ovaj niz funkcioniše, postoji mogućnost i za pravljenje grešaka. Zato postoji i lakši način pisanja istog koda, ali sa navodnicima ““.

char myStringSimple[] = "Manuel Radovanovic";

Pisanje stringa pod duplim navodnicima bez zareza i vitičasti zagrada je mnogo lakše. Čak nije ni potrebno da dodajete null karakter jer će kompajler to uraditi umesto vas. Vi možete deklarisati niz char i bez inicijalizacije, ali možete i odrediti unapred koliko elemenata ima vaš niz char. Obratite pažnju samo kada uzimate podatke od korisnika, tada treba da koristite ovakav pristup:

char myStringSimpleInput[19];
cin.get(myStringSimpleInput, 19);

Inače ako koristite samo naredbu cin da dodelite stringove, kod prvog praznog prostora će cin ubaciti null karakter i umesto rezultata Manuel Radovanovic, vaš rezultat će biti samo Manuel. Programski jezik C++ je nasledio biblioteku funkcija koje služe za rad sa stringovima poput strcpy() I strncpy() za kopiranje jednog stringa u drugi. Međutim ukoliko radite sa stringovima u C++ programskom jeziku, najbolje je da koristite klasu string, inače možete imati dosta bezbedonosni propusta i bagova u programu.

Šta je klasa string i kako se koristi? 

Microsoft Visual Studio se isporučuje sa kompajlerom koji sadrži biblioteku klasa za manipulaciju podacima. Mnogi kompajleri i drugih proizvođača takođe podržava standardne komponente class biblioteke. Ukoliko ste C# programer, ove klase nemojte mešati sa klasama .Net Framework-a iako imaju sličnosti. Zato, klasa string je jednostavno enkapsulirani set podataka i funkcija za manipulaciju string podataka. string klasu jednostavno koristite kad želite da radite sa stringovima. Da bi ste koristili klasu string u vašem programu ili klasi, dovoljno je da uvezete imenski prostor klase string ovako:

#include <string>

Sad možete manipulisati sa stringovima. Pogledajte kako se deklarišu i spajaju stringovi:

string firstName = "Manuel";
string lastName = "Radovanovic";
string whiteSpace = " ";

string fullName = firstName + whiteSpace + lastName;

Ovo možete napisati i ovako:

string fullName = firstName + “ “ + lastName;

Stringove možete spajati i funkcijuom append:

firstName.append(whitespace);
firstName.append(lastName);

Ukoliko imate string koji sadrži ime i prezime i vi želite da mu odbacite prezime, tada možete koristiti funkciju substr;

firstName = fullName.substr(0, 6);

Ovako će firstName string koji sadrži vrednost Manuel Radovanovic, posle funkcije substr; imati vrednost samo prvih 6 karaktera; Manuel. Ukoliko hoćete da vidite koliko firstName ima karaktera; koristite funkciju lenght.

short numberCharacters = firstName.length();

Ukoliko želite da prikažete svaki karakter pojedinačno, to se radi petljom.

for (short i = 0; i < fullName.length(); i++)
       {
             cout << "\t" << fullName[i] << endl;

       }

Međutim, da bi ste uvećali ili umanjili sva slova u stringu, prvo treba da uvezete locale klasu:

#include <locale>

Zatim je potrebno da napravite petlje koje će to odraditi:

locale loc;
       for (short i = 0; i < fullName.length(); i++)
       {
             fullName[i] = toupper(fullName[i], loc);

       }

       for (short i = 0; i < fullName.length(); i++)
       {
             fullName[i] = tolower(fullName[i], loc);

       }

Da bi ste nešto izbrisali iz stringa, koristite funkciju easer; da bi ste nove karaktere umetnuli u string, koristite funkciju insert; da bi ste zamenili vrednosti dve string promenjive, jednu sa drugom; koristite funkciju swap ili da bi ste zamenili određene stringove u stringu, koristite funkciju replace. Pogledajte kompletan kod programa Strings:





#include "stdafx.h"
#include <iostream>
#include <string>
#include <locale>
using namespace std;

int main()
{
       char myString[] = { 'M','a','n','u','e','l',' ','R','a','d','o','v','a','n','o','v','i','c','\0' };
       char myStringSimple[] = "Manuel Radovanovic";
       char myStringSimpleInput[19];
            
       cout << "USING STRINGS" << endl << endl;
      
       cout << "Use an array char myString[] with {'','',..}" << endl << endl << myString << endl << endl;
       cout << "Use an array char myString[] with \"\"" << endl << endl << myStringSimple << endl << endl;
      
       cout << "Input a string, up to maximum of 19 characters: ";
       cin.get(myStringSimpleInput, 19);
      
       cout << endl << "Input with cin.get( string, number of elements)."
              << endl << endl << myStringSimpleInput << endl << endl;

       system("PAUSE");
       system("cls");

       string firstName = "Manuel";
       string lastName = "Radovanovic";
       string whiteSpace = " ";
       string fullName = firstName + whiteSpace + lastName;

       cout << "firstName = \"" << firstName << "\"" << ";" << endl;
       cout << "lastName = \"" << lastName << "\"" << ";" << endl;
       cout << "whiteSpace = \" \"" << endl << endl;

       cout << "fullName = firstName + whiteSpace + lastName" << endl << endl << fullName << endl << endl;

       system("PAUSE");
       system("cls");

       cout << "append" << endl << endl;
       cout << "firstName.append(whiteSpace)" << endl << endl << firstName.append(whiteSpace) << endl << endl;
       cout << "firstName.append(lastName)" << endl << endl << firstName.append(lastName) << endl << endl;
      
       system("PAUSE");
       system("cls");
      
       cout << "substr" << endl << endl;
       cout << "firstName after append strings" << endl << firstName << endl << endl;
       firstName = firstName.substr(0, 6);
       cout << "firstName after substr(0, 6)" << endl << firstName << endl << endl;
      
       system("PAUSE");
       system("cls");
      
       cout << "lenght" << endl << endl;
       cout << "firstName has " << firstName.length() << " characters." << endl;
       cout << "whiteSpace has 1 character." << endl;
       cout << "lastName has " << lastName.length() << " characters." << endl << endl;
       cout << "fullName has " << fullName.length() << " characters." << endl << endl;

       system("PAUSE");
       system("cls");

       cout << "Use for statment to read string through elements" << endl << endl;
      
       for (short i = 0; i < fullName.length(); i++)
       {
             cout << "\t" << fullName[i] << endl;

       }
      
       cout << endl;
      
       system("PAUSE");
       system("cls");

       cout << "toupper" << endl << endl;

       locale loc;
       for (short i = 0; i < fullName.length(); i++)
       {
             fullName[i] = toupper(fullName[i], loc);

       }

       cout << fullName << endl << endl;

       system("PAUSE");
       system("cls");

       cout << "tolower" << endl << endl;

       for (short i = 0; i < fullName.length(); i++)
       {
             fullName[i] = tolower(fullName[i], loc);

       }

       cout << fullName << endl << endl;

       system("PAUSE");
       system("cls");

       cout << "erase, insert, swap, replace " << endl << endl << fullName << endl << endl;
      
       fullName = fullName.erase(6, 1);
       cout << "fullName.erase(6, 1);" << endl << fullName << endl << endl;
       fullName = fullName.insert(0, "www.");
       cout << "fullName.insert(0, \"www.\");" << endl << fullName << endl << endl;
       fullName = fullName.insert(fullName.length(), ".com");
       cout << "fullName.insert(fullName.length(), \".com\");" << endl << fullName << endl << endl;

       string thanks = "Thank you for visit my web page";
       fullName.swap(thanks);

       cout << "fullName.swap(thanks);" << endl << fullName << endl << endl;
       fullName = fullName.replace(23, fullName.length(),"blog");
       cout << "fullName.replace(23, fullName.length(),\"blog\");" << endl << endl << "\t" << fullName << endl << endl;
       cout << "\twww.manuelradovanovic.com" << endl << endl;
      
       system("PAUSE");
       return 0;

}

Kad pokrenete navedeni program, rezultati će biti ovakvi:

USING STRINGS

Use an array char myString[] with {'','',..}

Manuel Radovanovic

Use an array char myString[] with ""

Manuel Radovanovic

Input a string, up to maximum of 19 characters: Manuel Radovanovic

Input with cin.get( string, number of elements).

Manuel Radovanovic

Press any key to continue . . . 


--------------------------------------------------------------------------------------------------

firstName = "Manuel";
lastName = "Radovanovic";
whiteSpace = " "

fullName = firstName + whiteSpace + lastName

Manuel Radovanovic

Press any key to continue . . .



--------------------------------------------------------------------------------------------------




append

firstName.append(whiteSpace)

Manuel

firstName.append(lastName)

Manuel Radovanovic

Press any key to continue . . .


--------------------------------------------------------------------------------------------------

 substring

firstName after append strings

Manuel Radovanovic

firstName after substr(0, 6)

Manuel
 

Press any key to continue . . .

--------------------------------------------------------------------------------------------------

 lenght

firstName has 6 characters.
whiteSpace has 1 character.
lastName has 11 characters.

fullName has 18 characters.

Press any key to continue . . .

--------------------------------------------------------------------------------------------------

 Use for statment to read string through elements

M
a
n
u
e
l

R
a
d
o
v
a
n
o
v
i
c



 

Press any key to continue . . .
--------------------------------------------------------------------------------------------------

toupper

MANUEL RADOVANOVIC

Press any key to continue . . .



--------------------------------------------------------------------------------------------------

tolower

manuel radovanovic

Press any key to continue . . .

--------------------------------------------------------------------------------------------------

erase, insert, swap, replace

manuel radovanovic

fullName.erase(6, 1);

manuelradovanovic

fullName.insert(0, "www.");

www.manuelradovanovic

fullName.insert(fullName.length(), ".com");

www.manuelradovanovic.com

fullName.swap(thanks);

Thank you for visit my web page

fullName.replace(23, fullName.length(),"blog");

Thank you for visit my blog


www.manuelradovanovic.com


Press any key to continue . . .

Kako sve to izgleda možete pogledati i na video-u:

 

( C++ Tutorial - 15. Strings )





 


No comments:

Post a Comment