Articles by "Strings"
Showing posts with label Strings. Show all posts
no image
Character-Oriented I/O

We have discussed token-oriented input, performed when you use the operator  >> on streams and file streams.  Token-oriented input reads a token, an item (generally) separated from the next token by whitespace characters. We have also discussed line-oriented input, performed  by getline(), which reads an entire line of input.  C++ has a third kind of I/O, character-oriented I/O, which reads in or prints out one character at a time.  Character-oriented I/O is performed by the functions get() and put().

The get() Function
The  stream input function specifically designed for input of a single character value is get().  In its most common form, this function reads a single character (including a whitespace character; remember that whitespace characters are spaces, tabs and newline characters) from the keyboard   and returns it.  Typically, the value returned is assigned to a variable of type char.  

The general form of a call to get() to read a character from an input stream infile into a variable ch:

ch = infile.get();

• The stream can be a file stream, like infile, or it can be cin.
• If it attempts to read past the end of input, the stream variable gets a value indicating failure.

Why Do We Need get()?
You might ask why we need the get() function, since the extraction operator >> is capable of reading a character from a stream. The answer is that the extraction operator will not read whitespace characters. Suppose you want to read all the characters in this line and count them:

This is the string.
If you were to read this string character by character with the >> operator and count the characters, you would read in 16 characters. If you were to read it character by character with get(), you would read in 19 characters, counting the spaces. (And if you were to read it with getline(), you'd read the whitespace characters, but you'd read the whole string at once; and you couldn't count the characters as they are being read in.) 

no image
The Function change_one_line()

change_one_line() receives three parameters: line, oldstr, and newstr. It will replace each occurrence of oldstr in line by newstr. This is the most complicated of the functions. Good that we isolated it. Modular top-down programming.

The pseudocode follows:
receives line, oldstr, and newstr as parameters
while oldstr occurs in line
replace oldstr by newstr

Note:     
• pos = line.find(old,pos+newstr.length());
don’t want to find oldstring again if oldstring is part of newstring e.g cause and because. Would create infinite loop.

no image
Positions in a String and string::npos

The characters in a string have numbered positions, starting at 0, just like the values in an array. We can refer to the position (or index) of a character or a group of characters in a string. Remember, we start counting at 0. For example, here is the string "house" together with the position (or index) of each character.

We can use the position to access the value stored at that location.
string str = "house";
string::size_type len = str.length();
str[0] = 'm';                  
for (int i=0; i < len ; i++)          
cout << str[i] << endl;

If a function were to return the position of the letter 'u' in this string, it would return 2; similarly, the string "use" appears starting in position 2 of this string. The letter 'x' is not found. A function that tries to find something which is not present in a string returns string::npos. Can’t use 0 is used to indicate that a value is not found because 0 would mean position 0 of the string. The value npos is the maximum number of characters that a string can hold, which is one greater than the largest possible character position. (Notice that the string above has 5 characters, but the largest position is 4.)  The exact value of npos is machine dependent and irrelevant; what matters is that it represents a value which cannot be an index into the string.

no image
Finding the Position of a Character or a String within Another String: find()

Syntax: position = source.find(string_to_find, start_position);

find takes two parameters: the string to find, and the starting position.  It searches till the end of the string. find returns the position at which the item is found or string::npos if the item is not found. Reminder: find returns a value of type string::size_type, so declare the variable to hold the result that way.
no image
Deleting Part of the Value of a String: erase()

Removing characters from a string can be done using erase(). This member function takes two parameters, the starting position and the number of characters to remove. 
Syntax: source.erase(start_pos, numchars);

The erase() function removes the characters and closes up the string. If the second parameter is omitted, the function erases characters from the starting position to the end of the string.
no image
Extracting a Substring from a String: substr()

substr() extracts part of a string, leaving the original string unchanged. It takes two parameters of type string::size_type:  the first is the position to start extracting, and the second is the number of characters to extract.  It returns a substring consisting of the extracted characters. If you omit the second parameter, substr() will extract characters from the starting position and be continuing to the end of the string.
Syntax: result_string = source.substr(starting_pos,numchars);
no image
Data Type string::size_type

Many C++ string member functions return a numeric value which is not of type int.  The member functions size() and length() return a value which has type string::size_type. This is an unsigned integer type. (An unsigned integer can never be negative.) Suppose I want to store the length in a variable. I must declare the variable. It is more precise to declare it as type string::size_type rather than int. Note that to use this data type, size_type must be preceded by the word string and two colons:

string state = "New York";
string city = "Cincinnati";
string::size_type num1, num2 ;

num1 = state.length();  num1 is 8 (the space is counted)
num2 = city.size();     num2 is 10

Notes:
• We are using the names of the strings--state and city--to indicate what string object [variable] the member function should act upon. [to whom the function belongs?]
• It is safest to use string::size_type when referring to string sizes or to positions in a string.
no image
String operationsConcatenation and Comparing Strings

String operations in C++ are performed using some of the same operators that are used for arithmetic operations. The symbols are interpreted slightly differently in some cases. We've already seen the use of the = operator for assignment. 

Concatenating Strings:
It is possible to join two or more strings together using the + operator. Rather than addition, this use of the + operator joins one string to the end of another; this operation is called concatenation.
string str1, str2, str3;
str1 = "yesterday";
str2 = "morning";
str3 = str1+ " " + str2;
cout << str3 << endl; 
String str3 has the value "yesterday morning", and that value is sent to cout. 
Notes:
• It is necessary to concatenate a space between the two words to produce a space in the resulting string.  
• At least one of the operands must be a variable. [Useless to concatenate two literals.]
• The use of an operator (like +) for two different actions is called operator overloading. [not responsible this term]
string str = "train"; 
str = str + 's';
str has the value "trains". 
Note that it is also possible to use the += operator to perform concatenation:
str += 's';

Comparing Strings
You can compare two strings using the standard relational operators (<, <=, >, >=, ==, and !=). Two strings are the same (equal to each other) if they have the same number of characters and if each corresponding character matches: e.g., "cat" is the same as "cat" but not the same as "act", "Cat" or even as "cat " (with a space at the end). 
string str1 = "cat";
string str2 = "dog";
if (str1 == str2)
cout << "alike" << endl;
else
cout << "different" << endl;
   
This will, of course, print "different"  because "cat" is not the same string as "dog".  
Strings can be compared to determine whether one is greater than or less than the other. 
no image
String operations operator overloading

Different String operations:
i. = Equality 
ii. == String Copy 
iii. + Concatenation 
iv. << To display a string 
v. >> To reverse a string 
vi. Function to determine whether a string is a palindrome 
To find occurrence of a sub-strings. Use Operator Overloading.

Strings in C++: 
Strings can be defined as class objects which can be then manipulated like a built-in data types. Since the strings vary greatly in size, we use "new" to allocate memory for each string and a pointer variable to point to the string array. Thus we must create string objects that can hold these two pieces of information, namely length, and location which are necessary for string manipulations. A typical string class will look as 
class string 
char *p; 
int len; // length of string 
public:………….
// mem fun to initialize and manipulate strings 
………….. 
};

Pointers are used to allocate arrays dynamically i.e. we can decide the array size at runtime. 
c++ incorporates the option to use standard operators to perform operations with classes in addition to with fundamental types. For example: 
int a, b, c; 
a = b + c;
This is obviously valid code in C++ since the different variables of the addition are all fundamental types. Nevertheless, it is not so obvious that we could perform an operation similar to the following one:
struct 
string product; 
float price; 
a, b, c; 
a = b + c;
In fact, this will cause a compilation error, since we have not defined the behavior our class should have with addition operations. However, thanks to the C++ feature to overload operators, we can design classes able to perform operations using standard operators.


Thanks
Mukesh Rajput
no image
Important point about String in C++ programming:

1. What is a string?
A string is a sequence of one or more characters.

2. Write the syntax for declaration of a string.
syntax: char array_name [size]; Ex: char str [100];


3. State the difference between a null character and a null sting.
A null character indicates the end of the string.
A null string is a string with zero characters or no characters.

4. Which header file is needed to perform string operation?
#include<string.h>

5. Which header file is needed to perform character operations?
#include<ctype.h>

6. Write an example for string initialization.
char str[100] ={“CHANDIGARH CITY”};

7. What is the difference between gets() and scanf() function?
gets() function receives a string input up to the end of the line or a new line character. This means the string may have blank spaces and punctuation.
Scanf() function accepts a string only up to the first blank space or punctuation.


Thanks
Mukesh Rajput
no image
Write a C++ program to swap two strings, where each strings are entered by the user.

Program Code:
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int main()
{

char str1[20], str2[20], temp[20];
int i=0, j=0, k=0;
cout<<"Enter the First String : ";
gets(str1);
cout<<endl;
cout<<"Enter the Second String : ";
gets(str2);
cout<<endl;
while(str1[i]!='\0')
{
temp[j]=str1[i];
i++;
j++;
}
temp[j]='\0';
i=0, j=0;
while(str2[i]!='\0')
{
str1[j]=str2[i];
i++;
j++;
}
str1[j]='\0';
i=0, j=0;
while(temp[i]!='\0')
{
str2[j]=temp[i];
i++;
j++;
}
str2[j]='\0';
cout<<"Strings after swapping are : ";
cout<<endl;
cout<<"First String = "<<str1;
cout<<endl;
cout<<"Second String = "<<str2;
return 0;
}

The program output is tested on www.jdoodle.com
Output:

Enter the First String : Suruchika
Enter the Second String : Mukesh
Strings after swapping are : 
First String = Mukesh
Second String = Suruchika


Thanks
Mukesh Rajput
no image
Write a C++ program to sort different strings into alphabetic order, where strings are entered by user.

Program Code:
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int main()
{
char str[4][30], temp[30];
int i, j;
cout<<"Enter any four string to sort in alphabetical order : ";

cout<<endl;
for(i=0; i<4; i++)
{
cin>>str[i];
}
for(i=1; i<5; i++)
{
for(j=1; j<5; j++)
{
if(strcmp(str[j-1], str[j])>0)
{
strcpy(temp, str[j-1]);
strcpy(str[j-1], str[j]);
strcpy(str[j], temp);
}
}
}
cout<<"Strings in alphabetical order are : ";
cout<<endl;
for(i=0; i<4; i++)
{
cout<<str[i];
cout<<endl;
}
return 0;
}

The program output is tested on www.jdoodle.com
Output:
Enter any four string to sort in alphabetical order : 
Rajput
Mukesh
Thakur
Suruchika

Strings in alphabetical order are : 
Mukesh
Rajput
Suruchika
Thakur


Thanks
Mukesh Rajput
no image
Write a C++ Program to delete spaces from a sentence, where sentence is entered by the user.

Program Code:
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int main()
{
char str[80];
int i=0, len, j;

cout<<"Enter the sentence to delete space in it is: ";
gets(str);
cout<<endl;
len=strlen(str);
for(i=0; i<len; i++)
{
if(str[i]==' ')
{
for(j=i; j<len; j++)
{
str[j]=str[j+1];
}
len--;
}
}
cout<<"String after removing spaces in it is : ";
cout<<str;
return 0;
}

The program output is tested on www.jdoodle.com
Output:

Enter the sentence to delete space in it is: Mukesh Rajput Mukesh
String after removing spaces in it is : MukeshRajputMukesh


Thanks
Mukesh Rajput
no image
Write a C++ program to count number of words in the entered sentence.

Program Code:
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int main()
{
char strs[100], count=0, i, len;
cout<<"Enter the a sentence to count number of words in it is : ";
gets(strs);
cout<<endl;
len=strlen(strs);
for(i=0; i<len; i++)
{
if(strs[i]==' ')
{
count++;
}
}
cout<<"Total number of words in the entered sentence is : ";
cout<<count+1;
return 0;
}


The program output is tested on www.jdoodle.com
Output:
Enter the a sentence to count number of words in it is : Mukesh Rajput Mukesh
Total number of words in the entered sentence is : 3


Thanks
Mukesh Rajput
no image
Write a C++ program to find frequency of any character in a string,where string is entered by user.

Program Code:
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int main()
{
int i, count=0;
char str[100], ch;
cout<<"Enter the String to find frequency of character in it is : ";
gets(str);
cout<<endl;
cout<<"Enter a character to find its frequency in the given string : ";
cin>>ch;
cout<<endl;
for(i=0; str[i]!='\0'; i++)
{
if(ch==str[i])
{
count++;
}
}
cout<<"Frequency of the entered character in the given string is : ";

cout<<count;
return 0;
}

The program code is tested on www.jdoodle.com
Output:
Enter the String to find frequency of character in it is : MukeshMukeshMukesh
Enter a character to find its frequency in the given string : k
Frequency of the entered character in the given string is : 3


Thanks
Mukesh Rajput
no image
Write a C++ program to delete words from a sentence, where sentence is entered by user.

Program Code:
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int main()
{

int i, j = 0, k = 0, count = 0;
char str[100], str1[10][20], word[20];
cout<<"Enter the sentence to delete words from : ";
gets(str);
cout<<endl;
for (i=0; str[i]!='\0'; i++)
{
if (str[i]==' ')
{
str1[k][j] = '\0';
k++;
j=0;
}
else
{
str1[k][j]=str[i];
 j++;
}
}
str1[k][j] = '\0';
cout<<"Enter a word to be delete from the sentence : ";
cin>>word;
cout<<endl;
for (i=0; i<k+1; i++)
{
if (strcmp(str1[i], word) == 0)
{
for (j=i; j<k+1; j++)
{
strcpy(str1[j], str1[j + 1]);
k--;
}
}
}
cout<<"The new String after deleting the word from the sentence : ";
for (i=0; i<k+1; i++)
{
cout<<str1[i]<<" ";
}
return 0;
}

The program output is tested on www.jdoodle.com
Output:
Enter the sentence to delete words from : Mukesh Rajput Mukesh
Enter a word to be delete from the sentence : Mukesh
The new String after deleting the word from the sentence : Rajput 



Thanks
Mukesh Rajput
no image
Write a C++ program to delete vowels from a string, where string is entered by the user.

Program Code:
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int main()
{
char str[50];
int length, i, j;
cout<<"Enter a string to delete vowels from : ";
gets(str);
cout<<endl;
length = strlen(str);
for(i=0; i<length; i++)
{
if(str[i]=='a' || str[i]=='e' || str[i]=='i' || str[i]=='o' || str[i]=='u' || str[i]=='A' || str[i]=='E' || str[i]=='I' || str[i]=='O' || str[i]=='U')
{
for(j=i; j<length; j++)
{
str[j]=str[j+1];
}
length--;
}
}
cout<<"After deleting the vowels, the string will be : "<<str;

return 0;
}

The program output is tested on www.jdoodle.com
Output:
Enter a string to delete vowels from : Mukesh Rajput
After deleting the vowels, the string will be : Mksh Rjpt


Thanks
Mukesh Rajput