I need to write a program that asks the user to enter a string and then ask the user to enter a character. The following steps each need to have separate functions...
• Check the validity of the character
• The program should display the index number of the character
• The program should display the number of occurrences of the character
• The program should replace the character with a letter ‘T’ and display the new string
• Program should display the length of the string
• Program should convert the letter ‘T’ to ‘t’ and display the new string
I'm running into a problem when trying to display multiple indices; is there any way I can avert using pointers? I'm pretty sure I'm reinventing the wheel here...
//stringArray.cpp
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
using namespace std;
//prototypes
int isalpha( int ch );
bool validateChar(char);
char getChar();
int displayCharIndex(char [], int, char);
int getLength(char [] , int);
int main()
{
//Variables
char singleChar;
//int size = 0;
char charArray[50];
int stringLength;
int index = 0;
//main
cout << "Enter a string: ";
cin >> charArray;
cout << "\nYou entered " << charArray;
//enter char prompt
cout << "\n\nEnter an alphabetic character to search for within the string: ";
cin >> singleChar;
do
{
if (validateChar(singleChar))
{
cout << "\nThe character you entered, '" << singleChar << "' is valid.\n";
}
else
{
cout << "\nThe character you entered was not valid.\n\n";
singleChar = getChar();
}
}while(!validateChar(singleChar));
index = displayCharIndex(charArray, 50, singleChar);
cout << "\n\nThe index of the character is " << index;
//display number of occurrences of character
//replace the character with letter 'T' and display new string
stringLength = getLength(charArray, 50);
cout << "\n\nThe length of the string is " << stringLength;
//convert the letter 'T' to 't' and display string
cout << "\n\n";
system("PAUSE");
}
char getChar()
{
char input;
cout << "\n\nEnter an alphabetic character to search for within the string: ";
cin >> input;
return input;
}
//check validity of character
bool validateChar(char ch)
{
if(isalpha(ch))
return true;
else
return false;
}
//index of char in string
int displayCharIndex(char strArray[], int size, char ch)
{
cout << "**INDEXING**";
char *strchr( const char *str, int ch );
cout << "\n\nPointer = " << *strchr;
return *strchr;
}
//display length of the string
int getLength(char strArray[], int size)
{
int count = 0;
count = strlen(strArray);
return count;
}