| Marek (11) | |
| I have question.. better yet problem with string... Since i just started with string.. i was wondering how to dissolve a word into letters... Like when i write for example FISH... it gives me result L1=F L2=I L3=S L4=H... and if u could kindly write also a explanation about it. | |
|
|
|
| hamsterman (4327) | |||
|
Ar you asking about c-strings or std::string ? The general idea is the same for both though. A char can be accessed with []. example:
Then you have to iterate through the string (use for loop) and do this with every i, when i < string length. | |||
|
|
|||
| Null (777) | |||
What do you have so far? This isn't hard - first you need to get the length of the string and then loop each character:
Everything you need is here: http://www.cplusplus.com/reference/string/string/ EDIT: too slow | |||
|
Last edited on
|
|||
| Marek (11) | |
Thank you guys.. but i still need a bit of explanation....if it ain't a problemfor(int i=0;i<str.length();i++)Correct me if im wrong... as i figured this int i=0 is for Initialization i<str.length() is the lenght of the word goes to zero i++ every time it goes by one it gives a letter out i know this is a bit newbie question but... i am confused about this part :D | |
|
Last edited on
|
|
| mcleano (922) | |
|
If in doubt, always consult the documentation: http://www.cplusplus.com/doc/tutorial/control/ The for loop, in this example, is saying: 1) Create and initialize a variable to 0. 2) For as long as i is less than the length of the string ( str.lenth() ) 3) Increment i by one. In Null's example, he is printing individual letters of the string "aaa" using str[i]. This means that on the first iteration the variable i will be 0 so he will be printing str[0]. On the second iteration, the variable i will be 1 so he will be printing str[1]. On the third etc... | |
|
Last edited on
|
|
| Null (777) | |
|
See http://www.cplusplus.com/doc/tutorial/control/#for So yes, you are right. | |
|
|
|
| Marek (11) | |||
Ok now i got it...thank you all ...I have one more question... with this code
so basically i need to write out vowels but what bothers me is why doesn't it goes if( (i=='a')||(i=='e')...ect. but it goes if ( (unos[i]=='a')||(unos[i]=='e')...can somebody please explain it. (i found this on my schools web page). | |||
|
Last edited on
|
|||
| mcleano (922) | |||
Because the variable 'i' is an integer, and not a char in the string object. The term unos[i] refers to the element i+1 in the string object. Making a comparison of if(i=='a') would be saying, for example, if(0=='a'); for the first iteration at least. That code however is quite ugly. Try something more readable like:
| |||
|
Last edited on
|
|||