Strings C++
Jun 2, 2015 at 1:13pm UTC
Hi. I've got next problem. There was an exercise:
I must write a function void to_lower( char* s ) for replace all capitall letters with small letters in the sentence. For example: "Hello, world" to "hello world".
I can't use standart library functions.
There is my attempt:
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
#include <iostream>
#include <stdio.h>
#include <string.h>
int main()
{
char * s;
std::cout << "Enter a string: " ;
std::cin >> s;
char Alphabet[26];
int j = 0;
for ( char i = 'a' ; i < 'z' ; i++ ){
Alphabet[j++] = i;
}
for ( size_t n = 0; n < strlen( s ); n++ ){
for ( char i = 'a' ; i < 'z' ; i++ ){
if ( s[n] != i ){
int count = 0;
for ( char j = 'A' ; j < 'Z' ; j++ ){
count++;
if ( s[n] == j )
s[n] = Alphabet[count];
}
count = 0;
}
}
}
std::cout << "\nRes: " << s << std::endl;
}
The program exited without any visible errors.
Jun 2, 2015 at 1:27pm UTC
If you remember that the difference between the uppercase ASCII char and lowercase ASCII char is 32, i.e. a-A == 32, then you can simplify your code to:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include<iostream>
#include <string>
int main()
{
std::string s;
std::cout << "Enter a string: " ;
std::getline(std::cin, s);
for (int n = 0; n < s.length(); ++n)
{
if (s[n] >= 'A' && s[n] <= 'Z' )
s[n] += 32;
}
std::cout << "\nRes: " << s << std::endl;
return 0;
}
Jun 2, 2015 at 1:27pm UTC
s is uninitialized.
Jun 3, 2015 at 6:07pm UTC
Thanks!
Jun 3, 2015 at 11:46pm UTC
Note it is better to code it as
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#include<iostream>
#include <string>
const int offset = 'a' - 'A' ;
int main()
{
std::string s;
std::cout << "Enter a string: " ;
std::getline(std::cin, s);
for (int n = 0; n < s.length(); ++n)
{
if (s[n] >= 'A' && s[n] <= 'Z' )
s[n] += offset ;
}
std::cout << "\nRes: " << s << std::endl;
return 0;
}
Rather than use the "magic number" 32. Let the compiler do the work!
Andy
Topic archived. No new replies allowed.