Write a program

Pages: 12
Write your question here.

Please I need help with this question. I'm new to programming, and need to know this well before my end of semester exams.

Write a program that separates Uppercase letters from lowercase letters. Store values in array form. Compare the values in index. Kindly help with the code and full explanation. Thanks
What do you mean "separates Uppercase letters from lowercase letters". Can you show an example what do you have and what you should get arter prunning program?
If a word like ToM is input, it will seperate the uppercase letters TM from o
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cctype>


int main()
{
    char buffer[100];
    std::cin >> buffer;
    std::partition(buffer, buffer + std::strlen(buffer), isupper);
    std::cout << buffer;
}
ToM
TMo
Thanks a lot. it compiled well.
Can you kindly help with the explanation?
std::partition function moves all elements which conform some condition to the beginning.
First parameter is an iterator (pointer in your case) to the beginning of the range, second is iterator to one-past-the-end element (in your case beginning + amount of letters) and third is a function which return true if element should be first. In your case it is isupper function from <cctype>

http://en.cppreference.com/w/cpp/algorithm/partition
Thanks
closed account (j3Rz8vqX)
Write a program that separates Uppercase letters from lowercase letters.

Separate: (included 'other' array for sampling)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
using namespace std;
struct Collection{
public:
    string upper[100],lower[100];
    int upp, low;

    Collection(){upp=low=0;}//Constructor.
};
void parseString(string str, Collection &C)
{
    //Parse the string for uppers, lowers, and others:
    for(unsigned int i=0;i<str.size();i++)
    {
        if(str[i]>='A' && str[i]<='Z')
        {
            C.upper[C.upp]=str[i];
            ++C.upp;
        }
        else if(str[i]>='a' && str[i]<='z')
        {
            C.lower[C.low]=str[i];
            ++C.low;
        }
    }
}
void printString(string str[],int j)
{
    for(int i=0;i<j;i++)
        cout<<str[i];
    cout<<endl;
}
int main(){
    string str;
    Collection C;

    cout<<"Enter a sentence with uppercase and lowercase characters: \n\n: ";
    getline(cin, str);
    cout<<endl;

    parseString(str,C);
    printString(C.upper,C.upp);
    printString(C.lower,C.low);

    cout<<"Custom exit: Press enter: ";
    cin.get();
    return 0;
}
Enter a sentence with uppercase and lowercase characters:

: This is an example! Hello World!

THW
hisisanexampleelloorld
Custom exit: Press enter:

Differentiate: (simply upper and lower)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
using namespace std;
void parseString(string str, const char min, const char max)
{
    //Parse the string for uppers, lowers, and others:
    for(unsigned int i=0;i<str.size();i++)
    {
        if(str[i]>=min && str[i]<=max)
        {
            cout<<str[i];
        }
    }
    cout<<endl;
}
int main(){
    string str;

    cout<<"Enter a sentence with uppercase and lowercase characters: \n\n: ";
    getline(cin, str);
    cout<<endl;

    parseString(str,'A','Z');//Print the upper case characters
    parseString(str,'a','z');//Print the lower case characters

    cout<<"Custom exit: Press enter: ";
    cin.get();
    return 0;
}
Enter a sentence with uppercase and lowercase characters:

: Hello world, this is a string of characters! ADFSASD

HADFSASD
elloworldthisisastringofcharacters
Custom exit: Press enter: 

They are both separating, but one is literally, with arrays, and the other is implicitly through print schemes.
Thanks, can you please the one with arrays more?
closed account (j3Rz8vqX)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
using namespace std;

struct Collection{
public:
    char upper[100],lower[100];     //Modified: two arrays, of size 100, with value types of char
                                    //Used to store upper case characters and lowercase characters.
                                                            
    int upp, low;                   //Two counters to determine number of values in each array.

    Collection(){upp=low=0;}        //Default Constructor: defaulting data to 0, for safe use.
};
void parseString(string str, Collection &C)     //Our function to check through the string for upper and lower characters.
{
    //Parse the string for uppers, lowers:
    for(unsigned int i=0;i<str.size();i++)      //Continue this loop while "i" less than the strings size.
    {
        if(str[i]>='A' && str[i]<='Z')          //Check if the character is between 'A' and 'Z'; UPPERCASE
        {
            C.upper[C.upp]=str[i];              //IF so, assign our uppercase array, the character.
            ++C.upp;                            //Increment the upp counter; we have one letter more now!
        }
        else if(str[i]>='a' && str[i]<='z')
        {
            C.lower[C.low]=str[i];              //IF so, assign our uppercase array, the character.
            ++C.low;                            //Increment the low counter; we have one letter more now!
        }
    }
}
void printString(char ch[],int j)               //Our function to print the characters in our array
{                                               //The "j" argument being the limit for our following loop:
    for(int i=0;i<j;i++)                        //Loop while "i" is less than "j"; we only have j elements in this array.
        cout<<ch[i];                            //Print character at index "i"
    cout<<endl;                                 //Make a newline and flush the buffer.
}
int main(){
    string str;                                 //We're are using std::string to store the original string; not necessary,
                                                //A c string of char *str; would do just as well, but requires a lib for strlen();
                                                
    Collection C;                               //Creating our Collection object, and calling it "C".

    cout<<"Enter a sentence with uppercase and lowercase characters: \n\n: ";   //Prompt user for the string.
    getline(cin, str);                          //Use getline to get characters, including spaces, till "enter" is pressed.
    cout<<endl;                                 //Make a newline and flush the buffer.

    parseString(str,C);                         //Call the parseString function to create the lower and upper arrays.
    printString(C.upper,C.upp);                 //Print an array, in this case: upper; passing upper(array) and upp(size) as arguments.
    printString(C.lower,C.low);                 //Print an array, in this case: lower; passing lower(array) and low(size) as arguments.

    cout<<"Custom exit: Press enter: ";         //Console exit prompt, in case not ran from an IDE.
    cin.get();                                  //Wait for user to enter return key ("enter").
    return 0;
}


Procedural break down:

1) We first as the user for characters, till an "enter" was pressed.

2) We then operate on the string, looking for ASCII characters, in ranges of 'A' to 'Z' and 'a' to 'z'. http://www.asciitable.com/

3) If we find any, we copy its data into the appropriate array we had created for it; upper or lower. After each copy, we would increase the counter maintaining its usable size; anything beyond the counter hasn't been initialized and should not be used. Repeatedly doing this until we've checked the whole string entered by the user.

4) After that we will be printing the data from each array. To reduce code writing, we have created a function that takes an array of characters, and an integer, which tells us when to stop.

We should print the data and finish our task.

We finish up the program by asking the user to press enter, in case they are operating, directly, from the console and might possibly miss the output.

Receive the users input, and return 0 for a successful completion of the program.

The end.

*Changes: I've decided to change the string arrays in the object to character arrays since we are only parsing for single characters; string didn't hurt, but they weren't necessary for our case. Same applies to the print string function, it is now expecting an array of characters.

The main programs string variable could be changed into a c string, using pointer to characters, but I did not do so. If so, the programmer should include the <cstring> library and use strlen(str) instead of str.size() inside the parse strings function.
I wish this was the hardest my programming exams were!
Thanks bro. Bless you@dput
My first programming semester @erock88
Can you help with the flow chart?

Another version...

You can easily adapt it to ask user to enter the string rather than have it hard coded but string can only be max 100 chars otherwise you would run past the last index of the buffers (ive not put any checks in for that).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

#include <iostream>
using namespace std;

int main()
{
	char lowercase[100], uppercase[100];  // buffers for upper/lower
	int lIndex = 0, uIndex = 0;  // index position counters

	// test string
	char testArray[] = "This is a test string with some Capital Letters";

	// loop through array testing for upper/lower
	for (int i = 0; i < sizeof(testArray); i++)
	{
		if (islower(testArray[i]))   // is it lowercase?
			lowercase[lIndex++] = testArray[i];
		else
			if (isupper(testArray[i]))   // is it uppercase?
			uppercase[uIndex++] = testArray[i];
	}

	// null terminate the arrays
	lowercase[lIndex] = 0;
	uppercase[uIndex] = 0;

	// display them
	cout << "Uppercase: " << uppercase << endl;
	cout << "Lowercase: " << lowercase << endl;

	return 0;
}
Last edited on
closed account (j3Rz8vqX)
Much much smaller version
Absolutely true.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <cstring>// For strlen : c_string
using namespace std;

int main()
{
    char upper[100],lower[100];     //Two c_strings: upper and lower
    int upp=0, low=0;               //Two index counters: upp and low

    //String prompt:
    char str[100];
    cout<<"Enter a sentence with uppercase and lowercase characters: \n\n: ";
    cin.getline(str, 100);

    //Procedural Loop - Seek uppercases and lowercases:
    for(unsigned int i=0;i<strlen(str);i++)
    {
        if(str[i]>='A' && str[i]<='Z')
            upper[upp++]=str[i];
        else if(str[i]>='a' && str[i]<='z')
            lower[low++]=str[i];
    }

    //Add '\0' terminator for string printing
    upper[upp]='\0';
    lower[low]='\0';

    //Print c_strings:
    cout<<"Uppercase: "<<upper<<endl;
    cout<<"Lowercase: "<<lower<<endl;

    return 0;
}
Enter a sentence with uppercase and lowercase characters:

: Hello World
Uppercase: HW
Lowercase: elloorld

Process returned 0 (0x0)   execution time : 7.514 s
Press any key to continue.

The above is an implementation within main.
Beauty is in the eye of the beholder.

The main difference is the use of islower(testArray[i]) and isupper(testArray[i]), which is perfectly fine.

They're doing the same thing.

strlen: http://www.cplusplus.com/reference/cstring/strlen/
islower: http://www.cplusplus.com/reference/cctype/islower/
isupper: http://www.cplusplus.com/reference/cctype/isupper/
str[i]>='A' && str[i]<='Z' Will not work for all. You seem to assume that everything uses ASCII. Use of islower and isupper is less error-prone and more clear. Also Sean Parent cries looking at your code and your neglect of standard library.

Much much smaller version

I edited and removed that from my original post as when reading it back it looked like I was being cocky - text can always be read in the wrong context.

+1 MiiNiPaa
Even shorter version using two different containers (why won't use in-place partitioning), working with c-arrays (althrough they are unwieldy at best) and including non-letter safeguard.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <algorithm>
#include <cstring>
#include <cctype>
#include <iostream>

int main()
{
    char str[100], lowercase[100], uppercase[100];
    std::cout << "Enter a sentence with uppercase and lowercase characters: \n";
    std::cin.getline(str, 100);

    auto e = std::partition_copy(str, std::remove_if(str, str + strlen(str), 
                                          [](char t){return !std::isalpha(t);}),
                                 uppercase, lowercase, isupper);
    *e.first = *e.second = '\0';

    std::cout << "Uppercase: " << uppercase << '\n' <<
                 "Lowercase: " << lowercase << std::endl;
}
@MiiNiPaa Fine if OP has a C++ 11 compliant compiler
Pages: 12