You are here:

C++/string manipulation

Advertisement


Question
Hi
For the following program, I understand how to use strlen(), but I couldn't print out a string with *.  
This is the requirement:
The function strlen() will tell you the number of characters in a string.  use a for loop to print out a string the user enters with a * between each letter.  Assume a maximum input string of 20 characters.  
input: "Charlie"
output: "C*h*a*r*l*i*e

Any suggestions?
Thank you

Answer
Katrina,
The trick to solving this problem is using strlen() to determine the length of the string, then using that to determine how many times the 'for' loop should. Once you know the length of the string, you would have to use another string function to print out the entire string, one letter at a time. It might seem a bit confusing, so here's some sample code (you'll have to modify it given your specific style of coding or compiler to make it work, but you'll get the idea):

for(int i = 0; i < string_name.strlen(); i++) {

if (string_name.at(i) != string_name.strlen() {
cout << string_name.at(i) << "*";
}
else
cout << string_name.at(i);

}

So this loop will run, and print out every character in the string using the string_name.at() function (which is what I used back in the day). But there is a checker involved to make sure that when the last character is printed, no '*' is printed after the character. So you get "C*h*a*r*l*i*e" as oppose to "C*h*a*r*l*i*e*". I hope this gets you going on the right track, but if you have any questions or need some clarification, please don't hesitate to ask.

Best Of Luck,
Alan

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Alan F.

Expertise

Having problems with any basic or intermediate parts of C++? I can answer those questions for you using simple English. I have been taking C++ in school for a couple years, so I still remember what it was like to be a beginner (especially with C++, which is a difficult language)!

Experience

I have a C++ web page that discuses the basics of C++. The address is: http://www.afweb.net/complang/

©2016 About.com. All rights reserved.