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++ Language Fix this code to have it concatenate two strings st1 and st2 and put...
c++ Language Fix this code to have it concatenate two strings st1 and st2 and put the result in st3 with a space separator. it has to be done using array representation of strings #include <iostream> using namespace std; #include <string> int main() { string st1,st2, st3; int c = 0, i =0;    cout << "Enter a string: "; cin >> st1; cout << "Enter another string: "; cin >> st2;    while (st1[c] != '\0'){ st3[c] = st1[c];...
Write a program that prompts the user to input a string and outputs the string in...
Write a program that prompts the user to input a string and outputs the string in uppercase letters. (Use dynamic arrays to store the string.) my code below: /* Your code from Chapter 8, exercise 5 is below. Rewrite the following code to using dynamic arrays. */ #include <iostream> #include <cstring> #include <cctype> using namespace std; int main() { //char str[81]; //creating memory for str array of size 80 using dynamic memory allocation char *str = new char[80]; int len;...
There are two ways to write loops: (1) iterative, like the for-loops we're used to using,...
There are two ways to write loops: (1) iterative, like the for-loops we're used to using, and (2) recursive. Your prerequisite preparation for this course should have exposed you to both, although your working knowledge of recursive loops may not be as strong as that of iterative loops. Consider the following iterative function that prints an array of characters backward: #include <iostream> #include <cstring> // print an array backwards, where 'first' is the first index // of the array, and...
IN C Consider the following function whose purpose is to return an array of 3 strings...
IN C Consider the following function whose purpose is to return an array of 3 strings that are initialized to the strings in the character arrays s1, s2, and s3: #include #include char** stringstoarray(char* s1, char* s2, char* s3) { // dynamically allocate space for the pointer array itself. char** strings = fill in the blank strings[ 0 ] = strdup(s1); // initialize first string strings[ 1 ] = strdup(s2); // initialize first string strings[ 2 ] = strdup(s3); //...
I tried using the modulo to skip the chars but I doesnt work in some cases....
I tried using the modulo to skip the chars but I doesnt work in some cases. There are two ways to write loops: (1) iterative, like the for-loops we're used to using, and (2) recursive. Your prerequisite preparation for this course should have exposed you to both, although your working knowledge of recursive loops may not be as strong as that of iterative loops. Consider the following iterative function that prints an array of characters backward: #include #include // print...
Write a program that reads a string and outputs the number of lowercase vowels in the...
Write a program that reads a string and outputs the number of lowercase vowels in the string. Your program must contain a function with a parameter of a char variable that returns an int. The function will return a 1 if the char being passed in is a lowercase vowel, and a 0 for any other character. The output for your main program should be: There are XXXX lowercase vowels in string yyyyyyyyyyyyyyyyyyyyyy Where XXXX is the count of lowercase...
What is happening to my palindrome program? C++. Here is what my code does. I have...
What is happening to my palindrome program? C++. Here is what my code does. I have to strings. The user inputs into one of them. I use a for loop to enter the string into a second one in reverse. Then, I use strcmp to see if they are the same. If the output of strcmp is 0 the answer is trye, otherwise false. For some reason something is going really wrong with my copyString. I tried copying my for...
Please follow ALL the instructions and solve it by C++. Please and thank you! There are...
Please follow ALL the instructions and solve it by C++. Please and thank you! There are two ways to write loops: (1) iterative, like the for-loops we're used to using, and (2) recursive. Your prerequisite preparation for this course should have exposed you to both, although your working knowledge of recursive loops may not be as strong as that of iterative loops. Consider the following iterative function that prints an array of characters backward: #include <iostream> #include <cstring> // print...
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;   ...
Convert this C++ program exactly as you see it into x86 assembly language: // Use the...
Convert this C++ program exactly as you see it into x86 assembly language: // Use the Irvine library for the print function #include <iostream> // The string that needs to be printed char word[] = "Golf\0"; // Pointer to a specific character in the string char * character = word; //NOTE: This main() function is not portable outside of Visual Studio void main() { // Set up a LOOP - See the while loop's conditional expression below int ecx =...