Thanks to visit codestin.com
Credit goes to www.slideshare.net

Arrays and Strings
Arrays in C++
• An array is defined as collection of elements of same type, stored
in contiguous memory locations.
• Advantage of Arrays
• They make accessing elements easier by providing random access
• Sorting and searching operations are easy on arrays.
Arrays in C++
• Accessing array elements
• An individual element within an array is accessed by use of an
index.
• An index describes the position of an element within an array.
• Note: In C++ the first element has the index zero
Arrays in C++
• One dimensional Arrays
• A one-dimensional array is a list of
related variables. The general form of a
one-dimensional array declaration is:
datatype variable_name[size];
• datatype: base type of the array,
determines the data type of each element
in the array
• size: how many elements the array will
hold
• variable_name: the name of the array
#include <iostream>
using namespace std;
int main()
{
int array[] = {5, 6, 2, 3};
int size = sizeof(array)/sizeof(array[0]);
int k=0, reverse[size];
for(int i=size-1; i>=0;i--)
{
reverse[k++] = array[i];
}
for(int i=0; i<size; i++)
{
cout << reverse[i] <<" ";
}
return 0;
}
Output:
3 2 6 5
Arrays in C++
• Two dimensional Arrays
• The simplest form of a
multidimensional array is the two-
dimensional array.
• Here, we have a row index and a
column index. Both the row's and
column's index begins from 0
Syntax:
data_type variable_name[N][M]
data_type is the type of array, like int,
float, char, etc.
variable_name is the name of the array.
N is the number of rows.
M is the number of columns.
Arrays in C++
#include <iostream>
using namespace std;
int main()
{
int r1 = 2, c1 = 3;
int r2 = 3, c2 = 2;
int m1[r1][c1] = {{1, 2, 3},
{1, 1, 1}};
int m2[r2][c2] = {{1, 2},
{1, 3},
{1, 1}};
if(c1 != r2)
{
cout << "Matrix multiplaction Not ";}
else
{
int res[r1][c2];
for(int j=0; j<c2; j++){
int sum =0;
for(int k=0; k<r2; k++){
sum += (m1[i][k] * m2[k][j]);
}
res[i][j] = sum;
}
}
//output the resultant matrix
cout << "Resultant Matrix: n";
for(int i=0; i<r1; i++){
for(int j=0; j<c2; j++){
cout << res[i][j] << "t";
}
cout << "n";
}
}
return 0;
}
Strings in C++
• A String is called as group of characters enclosed in double quotes.
• String creations in C++
• C-style strings(The one-dimensional character array is used to store a string).
• Using string class
• C-style string creation
• A string is defined as a character array terminated by a null symbol ( ‘0’ ).
• Syntax:
char variablename[size];
• Example:
char s[20];
C-style Strings in C++
• Example:
• Reading input using cin
• Problem: Entering the string “This is a
test”, the above program only returns
“This”, not the entire sentence.
• Reason: The C++ input/output system
stops reading a string when the first
whitespace character is encountered.
• Solution: Use another C++ library
function, gets().
#include < iostream>
int main()
{
char str[80];
cout << “Enter a string: “;
cin >> str; // read string from keyboard
cout << “Here is your string: “;
cout << str;
return(0);
}
#include <iostream>
int main()
{
char str[80]; // long enough for user input?
cout << “Enter a string: “;
gets(str); // read a string from the
keyboard
cout << “Here is your string: “;
cout << str << endl;
return(0);
}
C-style Strings in C++
• C++ Library Functions for
Strings: The most common
are:
• strlen() : length of a string
• strcpy() : copy characters
from one string to another
• strcat() : concatenation of
strings
• strcmp() : comparison of
strings
String Length using function:
#include <iostream>
#include <cstring>
int main()
{
char str[80];
cout << “Enter a string: “;
gets(str);
cout << “Length is: “ << strlen(str);
return(0);}
String Length without using function:
#include<iostream>
using namespace std;
int main()
{
char s[20];
cin>>s;
int len=0;
for(int i=0;s[i]!='0';i++)
{ len++; }
cout<<"Length: "<<len;
}
C-style Strings in C++
• C++ Library Functions for
Strings: The most common
are:
• strcpy() : copy characters
from one string to another
• strcat() : concatenation of
strings
• strlen() : length of a string
• strcmp() : comparison of
strings
String Copy using function:
#include <iostream>
#include <cstring>
int main()
{
char a[10];
strcpy(a, “hello”);
cout << a;
return(0);
}
String Copy without using function:
#include<iostream>
using namespace std;
int main()
{
char s[20],s1[20];
cin>>s;
int i;
for(i=0;s[i]!='0';i++)
{
s1[i]=s[i];
}
s1[i]='0';
cout<<s1;
}
C-style Strings in C++
• C++ Library Functions for
Strings: The most common are:
• strcpy() : copy characters from
one string to another
• strcat() : concatenation of
strings
• strlen() : length of a string
• strcmp() : comparison of strings
String Concatenation
using function:
#include <iostream>
#include <cstring>
int main()
{
char s1[21], s2[11];
cin>>s1>>s2;
strcat(s1, s2);
cout << s1 << endl<< s2;
}
String Concatenation without
using function:
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char s1[20],s2[20];
cin>>s1>>s2;
int l1=strlen(s1);
int l2=strlen(s2);
int i;
for(i=0;s2[i]!='0';i++)
{
s1[l1++]=s2[i];
}
s1[l1]='0';
C-style Strings in C++
• strcmp() - Comparison of Strings: The
most common are:
• str_1 == str_2 : 0
• str_1 > str_2 : positive number
• str_1 < str_2 : negative number
• strncmp(s1,s2,n) function to compares the
first n number of characters between the
strings
• strlwr() function:
• This function is used to convert all
the characters in a string to lower
case letters
• strupr() function:
• This function is used to convert all
the characters in a string to lower
case letters
//string comparison using function
#include <iostream>
#include <cstring>
int main()
{ char str[60];
cout << “Enter password: “;
gets(str);
if(strcmp(str, “welcome@skcet”))
{
cout << “Invalid
password.n”;
}
else
{
cout << “Logged on.n”;
}
return(0);
}
//string comparison without using function
#include<iostream>
#include<cstring>
using namespace std;
int main()
{ char s1[20],s2[20];
cin>>s1>>s2;
int l1=strlen(s1);
int l2=strlen(s2);
int f=0;
if(l1==l2)
{
for(int i=0;s1[i]!='0';i++)
{
if(s1[i]==s2[i])
{ f++; }
else
{ break; }
}
}
if(f==l2)
{ cout<<"Equal"; }
else
{ cout<<"Not equal"; } }
C-style Strings in C++
• strchr() function:
• Find a character in a String and
return remaining string after it.
• strstr() function:
• The strstr() function in C++ finds
the first occurrence of a substring
in a string.
• If the substring is found, returns the pointer
to the first character of the substring .
• If the substring is not found, a null pointer
is returned.
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char s1[20],k;
cin>>s1>>k;
char *p=strchr(s1,k);
cout<<p;
}
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char s1[20],s2[20];
cin>>s1>>s2;
char *p=strstr(s1,s2);
if(p)
{ cout<<"Present"; }
else
{ cout<<"Not present"; }
}
C-style Strings in C++
• strrev() function:
• This function reverse the given
string.
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char s1[20];
cin>>s1;
strrev(s1);
cout<<endl<<s1;
}
Strings class in C++
• String using string class:
• The string class stores the characters as a
sequence of bytes with the functionality of
allowing access to the single-byte character
• In the case of strings, memory is allocated
dynamically. More memory can be allocated at
run time on demand. As no memory is
preallocated, no memory is wasted.
• Strings are slower when compared to
implementation than character array
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
getline(cin, str); // cin>>str;
cout << str << endl;
return 0;
}
Strings class functions in C++
• insert() function:
• This function inserts a string at a specified
location in the called string.
• append() function:
• This method appends one string at the
end of another string.
• erase() function:
• This function erases a single or multiple
character starting at a specified location
within the called string.
#include<iostream>
using namespace std;
int main()
{ string str("Hello");
str.insert(2, "rr");
cout<<"String after Insert : " << str<<endl;
string str1("Hello");
string str2("Hi");
str1.append(str2, 0, 10);
cout<<"String after append : " << str1<<endl;
string str3="Welcome";
str3.erase(3,2);
cout<<"String after erase : " << str3;
}
Strings class functions in C++
• length() function:
• This method gives us the total length
of a string.
• replace() function:
• This function replaces part of a string
with another string.
• at() function:
• This method gives us a character
present at a particular index in a
string.
#include<iostream>
using namespace std;
int main()
{ string str("Hello");
cout<<"String length : " << str.length()<<endl;
string str1("Hello");
string str2("test");
str1.replace(2,2,str2);
cout<<"String after replace : " << str1<<endl;
string str3="Welcome";
cout<<"Particular char in string : " << str3.at(3);
}
Output:
String length : 5
String after replace : Hetesto
Particular char in string : c
Strings class functions in C++
• swap() function:
• This method swaps one
string with the content
of another string.
• find() function:
• This method finds the
given string start index.
• substr() function:
• This method finds and
returns part of a string
i.e. substring.
#include<iostream>
using namespace std;
int main()
{ string str("Hello");
cout<<"Find given string index : " << str.find("ll")<<endl;
string str1("Hello");
string str2("test");
str1.swap(str2);
cout<<"String after swaping : " << str1<<" "<<str2<<endl;
string str3="Welcome";
cout<<"substring of string : " << str3.substr(1,5);
}
Output:
Find given string index : 2
String after swaping : test Hello
substring of string : elcom
Strings class functions in C++
• capacity() function:
• This method returns the total number
of elements that can be stored in a
string.
• empty() function:
• The empty() function returns 1 if string
is empty and 0 if it is not empty.
• push_back() function:
• This method is used to push (add)
characters at the end (back) of a string.
• pop_back() function:
• This method is used to pop (remove) 1
character from the end (back) of a
string.
#include<iostream>
using namespace std;
int main()
{ string str;
cout<<"Find empty string : " << str.empty()<<endl;
cout<<"Find capacity of string : "<<str.capacity()<<endl;
str="Find capacity of string";
cout<<"Find capacity of string : "<<str.capacity()<<endl;
string str1="Welcome";
str1.push_back('a');
cout<<"push_back of string : " <<str1 ;
str1.pop_back();
cout<<"string after pop_back : " << str1;
}
Output:
Find empty string : 1
Find capacity of string : 15
Find capacity of string : 30
push_back of string : Welcomea
string after pop_back : Welcome
Strings class functions in C++
• resize() function:
• The resize() function is used to
either increase or decrease the size
of a string.
• String copy, concatenation,
compare
#include<iostream>
using namespace std;
int main()
{ string str1="First";
string str2="Second";
string str3,str4;
//string copy
str3=str1;
cout<<"copy str1 ro str3:"<<str3<<endl;
//string concatenation
str4=str3+str2;
cout<<"concat str3 ro str2:"<<str4<<endl;
//string compare
if(str1==str2)
{ cout<<"str1 and str2 are equal"; }
else
{ cout<<"str1 and str2 are not equal"; }
}
Output:
copy str1 ro str3:First
concat str3 ro str2:FirstSecond
str1 and str2 are not equal
Strings class functions in C++
• String Iterator in C++:
• Iterators are used for
traversing or accessing all the
characters of a string.
• Iterator functions are
• begin() function and this gives
the beginning index of this
string
• end() This gives the ending
index of a string.
• ‘rbegin()’ and ‘rend()’ is
reverse begin and reverse end.
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string str = "Hello";
string:: iterator it;
for (it = str.begin (); it != str.end (); it++)
{
cout << *it;
}
cout << endl;
return 0;
}
Output:
Hello
#include <iostream>
using namespace std;
int main()
{
string str = "Hello";
string::reverse_iterator it;
for (it = str.rbegin (); it != str.rend (); it++)
{
cout << *it;
}
}
Output:
olleH
Strings class functions in C++
BASIS FOR
COMPARISON CHARACTER ARRAY STRING
Basic Character array is collection of variables, of
character data type.
String is class and variables of string are the
object of class "string".
Syntax char array_name [size]; string string_name;
Indexing An individual character in a character array
can be accessed by its index in array.
In string the particular character can be
accessed by the function
string_name.at(index)/ string_name[index]
Size Static Dynamic
Operators Operators in C++ can not be applied on
character array.
You may apply standard C++ operator on the
string.
Boundary Array boundaries are easily overrun. Boundaries will not overrun.
Access Fast accessing. Slow accessing.

3 (3)Arrays and Strings for 11,12,college.pptx

  • 1.
  • 2.
    Arrays in C++ •An array is defined as collection of elements of same type, stored in contiguous memory locations. • Advantage of Arrays • They make accessing elements easier by providing random access • Sorting and searching operations are easy on arrays.
  • 3.
    Arrays in C++ •Accessing array elements • An individual element within an array is accessed by use of an index. • An index describes the position of an element within an array. • Note: In C++ the first element has the index zero
  • 4.
    Arrays in C++ •One dimensional Arrays • A one-dimensional array is a list of related variables. The general form of a one-dimensional array declaration is: datatype variable_name[size]; • datatype: base type of the array, determines the data type of each element in the array • size: how many elements the array will hold • variable_name: the name of the array #include <iostream> using namespace std; int main() { int array[] = {5, 6, 2, 3}; int size = sizeof(array)/sizeof(array[0]); int k=0, reverse[size]; for(int i=size-1; i>=0;i--) { reverse[k++] = array[i]; } for(int i=0; i<size; i++) { cout << reverse[i] <<" "; } return 0; } Output: 3 2 6 5
  • 5.
    Arrays in C++ •Two dimensional Arrays • The simplest form of a multidimensional array is the two- dimensional array. • Here, we have a row index and a column index. Both the row's and column's index begins from 0 Syntax: data_type variable_name[N][M] data_type is the type of array, like int, float, char, etc. variable_name is the name of the array. N is the number of rows. M is the number of columns.
  • 6.
    Arrays in C++ #include<iostream> using namespace std; int main() { int r1 = 2, c1 = 3; int r2 = 3, c2 = 2; int m1[r1][c1] = {{1, 2, 3}, {1, 1, 1}}; int m2[r2][c2] = {{1, 2}, {1, 3}, {1, 1}}; if(c1 != r2) { cout << "Matrix multiplaction Not ";} else { int res[r1][c2]; for(int j=0; j<c2; j++){ int sum =0; for(int k=0; k<r2; k++){ sum += (m1[i][k] * m2[k][j]); } res[i][j] = sum; } } //output the resultant matrix cout << "Resultant Matrix: n"; for(int i=0; i<r1; i++){ for(int j=0; j<c2; j++){ cout << res[i][j] << "t"; } cout << "n"; } } return 0; }
  • 7.
    Strings in C++ •A String is called as group of characters enclosed in double quotes. • String creations in C++ • C-style strings(The one-dimensional character array is used to store a string). • Using string class • C-style string creation • A string is defined as a character array terminated by a null symbol ( ‘0’ ). • Syntax: char variablename[size]; • Example: char s[20];
  • 8.
    C-style Strings inC++ • Example: • Reading input using cin • Problem: Entering the string “This is a test”, the above program only returns “This”, not the entire sentence. • Reason: The C++ input/output system stops reading a string when the first whitespace character is encountered. • Solution: Use another C++ library function, gets(). #include < iostream> int main() { char str[80]; cout << “Enter a string: “; cin >> str; // read string from keyboard cout << “Here is your string: “; cout << str; return(0); } #include <iostream> int main() { char str[80]; // long enough for user input? cout << “Enter a string: “; gets(str); // read a string from the keyboard cout << “Here is your string: “; cout << str << endl; return(0); }
  • 9.
    C-style Strings inC++ • C++ Library Functions for Strings: The most common are: • strlen() : length of a string • strcpy() : copy characters from one string to another • strcat() : concatenation of strings • strcmp() : comparison of strings String Length using function: #include <iostream> #include <cstring> int main() { char str[80]; cout << “Enter a string: “; gets(str); cout << “Length is: “ << strlen(str); return(0);} String Length without using function: #include<iostream> using namespace std; int main() { char s[20]; cin>>s; int len=0; for(int i=0;s[i]!='0';i++) { len++; } cout<<"Length: "<<len; }
  • 10.
    C-style Strings inC++ • C++ Library Functions for Strings: The most common are: • strcpy() : copy characters from one string to another • strcat() : concatenation of strings • strlen() : length of a string • strcmp() : comparison of strings String Copy using function: #include <iostream> #include <cstring> int main() { char a[10]; strcpy(a, “hello”); cout << a; return(0); } String Copy without using function: #include<iostream> using namespace std; int main() { char s[20],s1[20]; cin>>s; int i; for(i=0;s[i]!='0';i++) { s1[i]=s[i]; } s1[i]='0'; cout<<s1; }
  • 11.
    C-style Strings inC++ • C++ Library Functions for Strings: The most common are: • strcpy() : copy characters from one string to another • strcat() : concatenation of strings • strlen() : length of a string • strcmp() : comparison of strings String Concatenation using function: #include <iostream> #include <cstring> int main() { char s1[21], s2[11]; cin>>s1>>s2; strcat(s1, s2); cout << s1 << endl<< s2; } String Concatenation without using function: #include<iostream> #include<cstring> using namespace std; int main() { char s1[20],s2[20]; cin>>s1>>s2; int l1=strlen(s1); int l2=strlen(s2); int i; for(i=0;s2[i]!='0';i++) { s1[l1++]=s2[i]; } s1[l1]='0';
  • 12.
    C-style Strings inC++ • strcmp() - Comparison of Strings: The most common are: • str_1 == str_2 : 0 • str_1 > str_2 : positive number • str_1 < str_2 : negative number • strncmp(s1,s2,n) function to compares the first n number of characters between the strings • strlwr() function: • This function is used to convert all the characters in a string to lower case letters • strupr() function: • This function is used to convert all the characters in a string to lower case letters //string comparison using function #include <iostream> #include <cstring> int main() { char str[60]; cout << “Enter password: “; gets(str); if(strcmp(str, “welcome@skcet”)) { cout << “Invalid password.n”; } else { cout << “Logged on.n”; } return(0); } //string comparison without using function #include<iostream> #include<cstring> using namespace std; int main() { char s1[20],s2[20]; cin>>s1>>s2; int l1=strlen(s1); int l2=strlen(s2); int f=0; if(l1==l2) { for(int i=0;s1[i]!='0';i++) { if(s1[i]==s2[i]) { f++; } else { break; } } } if(f==l2) { cout<<"Equal"; } else { cout<<"Not equal"; } }
  • 13.
    C-style Strings inC++ • strchr() function: • Find a character in a String and return remaining string after it. • strstr() function: • The strstr() function in C++ finds the first occurrence of a substring in a string. • If the substring is found, returns the pointer to the first character of the substring . • If the substring is not found, a null pointer is returned. #include<iostream> #include<cstring> using namespace std; int main() { char s1[20],k; cin>>s1>>k; char *p=strchr(s1,k); cout<<p; } #include<iostream> #include<cstring> using namespace std; int main() { char s1[20],s2[20]; cin>>s1>>s2; char *p=strstr(s1,s2); if(p) { cout<<"Present"; } else { cout<<"Not present"; } }
  • 14.
    C-style Strings inC++ • strrev() function: • This function reverse the given string. #include<iostream> #include<cstring> using namespace std; int main() { char s1[20]; cin>>s1; strrev(s1); cout<<endl<<s1; }
  • 15.
    Strings class inC++ • String using string class: • The string class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character • In the case of strings, memory is allocated dynamically. More memory can be allocated at run time on demand. As no memory is preallocated, no memory is wasted. • Strings are slower when compared to implementation than character array #include <iostream> #include <string> using namespace std; int main() { string str; getline(cin, str); // cin>>str; cout << str << endl; return 0; }
  • 16.
    Strings class functionsin C++ • insert() function: • This function inserts a string at a specified location in the called string. • append() function: • This method appends one string at the end of another string. • erase() function: • This function erases a single or multiple character starting at a specified location within the called string. #include<iostream> using namespace std; int main() { string str("Hello"); str.insert(2, "rr"); cout<<"String after Insert : " << str<<endl; string str1("Hello"); string str2("Hi"); str1.append(str2, 0, 10); cout<<"String after append : " << str1<<endl; string str3="Welcome"; str3.erase(3,2); cout<<"String after erase : " << str3; }
  • 17.
    Strings class functionsin C++ • length() function: • This method gives us the total length of a string. • replace() function: • This function replaces part of a string with another string. • at() function: • This method gives us a character present at a particular index in a string. #include<iostream> using namespace std; int main() { string str("Hello"); cout<<"String length : " << str.length()<<endl; string str1("Hello"); string str2("test"); str1.replace(2,2,str2); cout<<"String after replace : " << str1<<endl; string str3="Welcome"; cout<<"Particular char in string : " << str3.at(3); } Output: String length : 5 String after replace : Hetesto Particular char in string : c
  • 18.
    Strings class functionsin C++ • swap() function: • This method swaps one string with the content of another string. • find() function: • This method finds the given string start index. • substr() function: • This method finds and returns part of a string i.e. substring. #include<iostream> using namespace std; int main() { string str("Hello"); cout<<"Find given string index : " << str.find("ll")<<endl; string str1("Hello"); string str2("test"); str1.swap(str2); cout<<"String after swaping : " << str1<<" "<<str2<<endl; string str3="Welcome"; cout<<"substring of string : " << str3.substr(1,5); } Output: Find given string index : 2 String after swaping : test Hello substring of string : elcom
  • 19.
    Strings class functionsin C++ • capacity() function: • This method returns the total number of elements that can be stored in a string. • empty() function: • The empty() function returns 1 if string is empty and 0 if it is not empty. • push_back() function: • This method is used to push (add) characters at the end (back) of a string. • pop_back() function: • This method is used to pop (remove) 1 character from the end (back) of a string. #include<iostream> using namespace std; int main() { string str; cout<<"Find empty string : " << str.empty()<<endl; cout<<"Find capacity of string : "<<str.capacity()<<endl; str="Find capacity of string"; cout<<"Find capacity of string : "<<str.capacity()<<endl; string str1="Welcome"; str1.push_back('a'); cout<<"push_back of string : " <<str1 ; str1.pop_back(); cout<<"string after pop_back : " << str1; } Output: Find empty string : 1 Find capacity of string : 15 Find capacity of string : 30 push_back of string : Welcomea string after pop_back : Welcome
  • 20.
    Strings class functionsin C++ • resize() function: • The resize() function is used to either increase or decrease the size of a string. • String copy, concatenation, compare #include<iostream> using namespace std; int main() { string str1="First"; string str2="Second"; string str3,str4; //string copy str3=str1; cout<<"copy str1 ro str3:"<<str3<<endl; //string concatenation str4=str3+str2; cout<<"concat str3 ro str2:"<<str4<<endl; //string compare if(str1==str2) { cout<<"str1 and str2 are equal"; } else { cout<<"str1 and str2 are not equal"; } } Output: copy str1 ro str3:First concat str3 ro str2:FirstSecond str1 and str2 are not equal
  • 21.
    Strings class functionsin C++ • String Iterator in C++: • Iterators are used for traversing or accessing all the characters of a string. • Iterator functions are • begin() function and this gives the beginning index of this string • end() This gives the ending index of a string. • ‘rbegin()’ and ‘rend()’ is reverse begin and reverse end. #include <iostream> #include <string.h> using namespace std; int main() { string str = "Hello"; string:: iterator it; for (it = str.begin (); it != str.end (); it++) { cout << *it; } cout << endl; return 0; } Output: Hello #include <iostream> using namespace std; int main() { string str = "Hello"; string::reverse_iterator it; for (it = str.rbegin (); it != str.rend (); it++) { cout << *it; } } Output: olleH
  • 22.
    Strings class functionsin C++ BASIS FOR COMPARISON CHARACTER ARRAY STRING Basic Character array is collection of variables, of character data type. String is class and variables of string are the object of class "string". Syntax char array_name [size]; string string_name; Indexing An individual character in a character array can be accessed by its index in array. In string the particular character can be accessed by the function string_name.at(index)/ string_name[index] Size Static Dynamic Operators Operators in C++ can not be applied on character array. You may apply standard C++ operator on the string. Boundary Array boundaries are easily overrun. Boundaries will not overrun. Access Fast accessing. Slow accessing.