Question

Strings The example program below, with a few notes following, shows how strings work in C++....

Strings

The example program below, with a few notes following, shows how strings work in C++.

Example 1:

#include <iostream> using namespace std; int main()
{

string s="eggplant";
string t="okra";
cout<<s[2]<<endl;
cout<< s.length()<<endl; ​//prints 8
cout<<s.substr(1,4)<<endl; ​//prints ggpl...kind of like a slice, but the second num is the length of the

piece
cout<<s+t<<endl; //concatenates: prints eggplantokra cout<<s+"a"<<endl;
cout<<s.append("a")<<endl; ​//prints eggplanta: see Note 1 below

//cout<<s.append(t[1])<<endl; ​//an error; see Note 1

cout<<s.append(t.substr(1,1))<<endl; ​//prints eggplantak; see Note 1 cout<<s.find("gg")<<endl;
if (s.find("gg")!=-1)

cout<<"found gg"<<endl;
else cout<<"gg not found"<<endl; if (s.find("xx")!=-1)

cout<<"found xx"<<endl;
else cout<<"xx not found"<<endl;
cout<<s.find('p')<<endl; ​//prints 3: find will work with a single character

return 0;

//prints "g"... see Note 0 below

}

Note 0: ​When you use an index with a string in C++ you do not get a string, but a different thing: a single character. C++ does NOT treat a single character as just a string with one thing in it, but as a different animal.

Note 1:​ In C++, append() is more like concatenate, in that the thing you append on has to be string, and can't be a single character.

For example, suppose we wanted to add the second character of the string t onto the end of string s. We can't write

s.append(t[1]);

because t[1] isn't a string, it's a single character (see Note 0). Instead we have to write

s.append(t.substr(1,1));

This works because substr() gives us a string of length 1, not a single character.

When find() doesn't find anything, it returns a funny large number, as the printout shows, but fortunately that large number tests as equal to -1. Don't expect that to make sense!

C-strings

C++ actually has two ways of managing collections of characters. We've been discussion "strings" above, and there are also c-strings, which work differently.

Actually, anytime you write something inside double quotes in your programs you're creating a c-string, without knowing it. Strings are actually objects (something you'll learn about soon). C-strings are simpler, just arrays of characters.

C++ has a data type char, for character. A char information holder takes up one byte, and can store one character, such as a letter, a digit, or a punctuation mark. A c-string is just an array of characters, like this, say,

char s[100];
but it is managed in a special, clever way, that it's important to know about.

The thing about character strings is that you don't want to worry ahead of time about exactly how long they are. If someone is going to type in a file name, you don't want to tell them it has to be exactly so many characters long. Rather, you want to be able to deal with as many characters as they choose to type, up to some limit.

The C++ designers (well, actually it was the C designers, or someone even earlier) came up with a way to do this: they put a special marker character into every c-string to mark its end.

The end marker is the character code 0, which is not a legal code for any character. So there is no risk of cutting off any legitimate c-string when using this as the marker.

The idea is simple. If a c-string is empty, the marker character is sitting right in the first slot. It doesn't matter what's in the rest of the slots, because anybody processing the c-string stops when they see the marker. If the c-string contains the word eggplant, the first eight slots in the array contain the letters e, g, g, p, l, a, n, t, and then the next slot contains the marker character.

When you print out a c-string, as in cout<<s;

the code for << knows to stop when it gets to the marker character, so only the good stuff in s gets printed.

Example 2:

#include <iostream> using namespace std;

int main() {

char cstring[]="eggp ant";
cout << cstring<< endl;

//note that a char array can have a blank in it

int i=0;
while(cstring[i]!=0) //have to use a while, not a for, when don't know how

//long the array is

{
cout<<cstring[i]<<endl; i=i+1;

}

for(int i=0;i<12;i++) //deliberately going too far in this for to see everything in cstring plus a little extra

cout<<"<"<<cstring[i]<<">"<<int(cstring[i])<<endl; //print the chars and the int codes for them

return 0; }

Running this produces this output (with comments added)

eggp ant //notice that the whole c-string is printed, including the space e
g
g

p

a
n
t​ //note that the loop stops when it comes to the end marker, because of our while()... we don't print any garbage characters, including the marker
<e>101
<g>103
<g>103
<p>112
< >32
<a>97
<n>110
<t>116
<0>0 //! this is the marker character
<0>0
<0>0 //these other zeros are just left over in memory
<0>0

Pass by Reference

Pass by Value

Pass by Reference

Passes an argument by value.

Passes an argument by reference.

You are sending a copy of the data to the function.

You are passing the memory address of the data.

Changes does not affect the actual value.

Changes to the value affect the original data.

Example 3:

#include <iostream>
using namespace std;
 void printnumbers(int &a, int b)
{
  a=1500;
  b=40;

}
int main () {

   int a = 5;
   int b = 10;
cout << "The value of a is: " << a << endl;
   cout << "The value of b is: " << b << endl;
   printnumbers(a, b);
   cout << "The value of a is: " << a << endl;
   cout << "The value of b is: " << b << endl;

return 0; }

Recitation 5 Activity:

This question is related to string operations to find if a given string is Palindrome and Anagram.

Homework Answers

Answer #1

Here is the program from which you can identify palindrome string.

#include<iostream>
using namespace std;

int main( )
{
char str[80];

cout<<"Enter string: ";
cin.getline(str, 80);
  
int l; //length of string
  
//check length of string
for(l = 0; str[l] != '\0'; l++);

//Comparing first element with last element till middle of string
int i;
for(i = 0; (i < l/2) && (str[i] == str[l - i - 1]); i++);

if(i == l/2)
cout << "Palindrome";
else
cout << "Not a palindrome";
  
return 0;
}

For Anagram string :

#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
   clrscr();
   char str1[20],str2[20];
   int len,len1,len2,i,j,found=0,not_found=0;
   cout<<"Enter first string :";
   gets(str1);
   cout<<"Enter second string :";
   gets(str2);
   len1=strlen(str1);
   len2=strlen(str2);
   if(len1==len2)
   {
       len=len1;
       for(i=0;i<len;i++)
       {
           found=0;
           for(j=0;j<len;j++)
           {
               if(str1[i]==str2[j])
               {
                   found=1;
                   break;
               }
           }
           if(found==0)
           {
               not_found=1;
               break;
           }
       }
       if(not_found==1)
       {
           cout<<"Strings are not Anagram to each other";
       }
       else
       {
           cout<<"Strings are Anagram";
       }
   }
   else
   {
       cout<<"Two string must have same number of character to be Anagram";
   }
   getch();
}

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
C++ visual studios this function has to run twice. and the "count" variable needs to be...
C++ visual studios this function has to run twice. and the "count" variable needs to be "2" on the second run. How can i do that? The parameters can not change as well void printArray(const int *array, int n) {    int count = 1;    char check;    if (check == 'k')    {        count++;    }    cout << "Value " << count << " array contents." << endl;    cout << "------------------------" << endl;   ...
C Program Write a program to count the frequency of each alphabet letter (A-Z a-z, total...
C Program Write a program to count the frequency of each alphabet letter (A-Z a-z, total 52 case sensitive) and five special characters (‘.’, ‘,’, ‘:’, ‘;’ and ‘!’) in all the .txt files under a given directory. The program should include a header count.h, alphabetcount.c to count the frequency of alphabet letters; and specialcharcount.c to count the frequency of special characters. Please only add code to where it says //ADDCODEHERE and keep function names the same. I have also...
Please write variables and program plan (pseudocode) of the C++ programming below: #include <iostream> #include <cmath>...
Please write variables and program plan (pseudocode) of the C++ programming below: #include <iostream> #include <cmath> using namespace std; void divisors(int num); int main () {    char repeat;    int num;       while (repeat !='n')    {        cout << "Enter a number: ";        cin >> num;        divisors(num);        cout << "Continue? (y or n): ";        cin >> repeat;    }    return 0; } void divisors(int num) {   ...
For a C program hangman game: Create the function int setup_game [int setup_game ( Game *g,...
For a C program hangman game: Create the function int setup_game [int setup_game ( Game *g, char wordlist[][MAX_WORD_LENGTH], int numwords)] for a C program hangman game. (The existing code for other functions and the program is below, along with what the function needs to do) What int setup_game needs to do setup_game() does exactly what the name suggests. It sets up a new game of hangman. This means that it picks a random word from the supplied wordlist array and...
Task 2: Compare strings. Write a function compare_strings() that takes pointers to two strings as inputs...
Task 2: Compare strings. Write a function compare_strings() that takes pointers to two strings as inputs and compares the character by character. If the two strings are exactly same it returns 0, otherwise it returns the difference between the first two dissimilar characters. You are not allowed to use built-in functions (other than strlen()) for this task. The function prototype is given below: int compare_strings(char * str1, char * str2); Task 3: Test if a string is subset of another...
Using the following code perform ALL of the tasks below in C++: ------------------------------------------------------------------------------------------------------------------------------------------- Implementation: Overload input...
Using the following code perform ALL of the tasks below in C++: ------------------------------------------------------------------------------------------------------------------------------------------- Implementation: Overload input operator>> a bigint in the following manner: Read in any number of digits [0-9] until a semi colon ";" is encountered. The number may span over multiple lines. You can assume the input is valid. Overload the operator+ so that it adds two bigint together. Overload the subscript operator[]. It should return the i-th digit, where i is the 10^i position. So the first...
C++ PROGRAM When I input 3 S P R, it was suppoesed to pop up L...
C++ PROGRAM When I input 3 S P R, it was suppoesed to pop up L W T. But it showed L L L.IDK why the moveNo is not working. I am asking for help, plz dont put some random things on it. main.cpp #include <iostream> #include "computer.h" #include "human.h" #include "referee.h" using namespace std; int main() {     human h;     computer c;     referee r;     r.compare(h,c);     return 0; } computer.cpp #include<iostream> #include "computer.h" using namespace std;...
C++ question. Please explain the code and how it resulted in the output. Explain each line...
C++ question. Please explain the code and how it resulted in the output. Explain each line along with the aspects of "buffers" if possible. Everything is listed below. Code below: #include <iostream> #include <string> using namespace std; int main() {    cout << boolalpha;    cout << static_cast<bool>(1) << endl;    cout << static_cast<bool>(0) << endl;    string s = "AAARGH!!!";    if (s.find("AAA")) { cout << 1 << endl; }    if (s.find("RGH")) { cout << 2 << endl;...
in C++ Need a heap-sort function #include <iostream> #include <stdlib.h> #include <string> using namespace std; void...
in C++ Need a heap-sort function #include <iostream> #include <stdlib.h> #include <string> using namespace std; void MyFunc ( int *array ) { // Your code here ----------------- } int main(int argc,char **argv) { int *Sequence; int arraySize; // Get the size of the sequence cin >> arraySize; // Allocate enough memory to store "arraySize" integers Sequence = new int[arraySize];    // Read in the sequence for ( int i=0; i<arraySize; i++ ) cin >> Sequence[i]; // Run your algorithms to...
Quick sort func in C++ #include <iostream> #include <stdlib.h> #include <string> using namespace std; void MyFunc...
Quick sort func in C++ #include <iostream> #include <stdlib.h> #include <string> using namespace std; void MyFunc ( int *array ) { // Code here } int main(int argc,char **argv) { int *Sequence; int arraySize; // Get the size of the sequence cin >> arraySize; // Allocate enough memory to store "arraySize" integers Sequence = new int[arraySize];    // Read in the sequence for ( int i=0; i<arraySize; i++ ) cin >> Sequence[i]; // Run your algorithms to manipulate the elements...