0

The first initial was easily isolated and capitalized. My problem is getting the next initial. I am trying to sweep through the string in search for a space, then get and print the next initial. I'm using strchr to find "space" between words. After several hours can't figure out how to use this function - maybe this is not even the best function to use... Help please!

enter image description here

3
  • execute man strchr in the terminal to know what this function does and what it returns. – kzidane Jun 3 '15 at 19:55
  • I would just like to say thanks. I was having the same issue. I was thinking into it too much, had twice as much code and only accomplished half the solution. Thanks again... – user7317 Jun 12 '15 at 13:57
  • I would also like to extend my gratitude. I had serious code going on and this was way easier! I also over-thought the whole process and my code kept getting longer and longer, and although my code compiled and functioned it was only partially correct. Thanks again for this solution! – Ty Powell Jun 15 '15 at 10:37
0

Well, you went on searching for space (32) in the string everytime, so that's like O(n) for strchr and then calling that another n times will lead you to O(n2), which is actually bad.

I won't discourage you to use strchr, but writing code for such small stuff instead of using built-in functions especially when one is new to programming is a better practice IMO.

BTW How does this look, short and simple.

string s = GetString();
for (i = 0 ; s[i] != '\0' ; ++i)
{
    if (i == 0 || s[i-1] == ' ')
        printf("%c", toupper(s[i]));
    else
        printf("%c", s[i]);
}

Convert everything to upper case that either occurs after a space or is the first character. This solution runs in O(n).

Hope that helps. Good Luck.

5
  • Thanks for your help and comments. I tried it but i'm not getting what I need which is print initials only. That code capitalizes letters. – Robert R. Jun 3 '15 at 14:50
  • 1
    But if you look closer at sinister's code, it does everything you want. Think about it. What if you removed the else clause? What would it do? And if you didn't want the capitals, how would you change it? – Cliff B Jun 3 '15 at 20:42
  • Comment the else part in that code, and you will get what you want to achieve. – sinister Jun 4 '15 at 3:14
  • You guys are right! Thanks! It took me a few days to get back to the problem because I was travelling but now it's done. – Robert R. Jun 8 '15 at 0:02
  • Accept the answer if that worked for you – sinister Jun 8 '15 at 0:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .