String help
Jul 26, 2013 at 2:26pm UTC
How can I check how many characters are there in a string using an array.
I got this far, but I am not sure what to put for the condition.
1 2 3 4
for (int i = 0; ; i++)
{
...
}
Thank you!
Jul 26, 2013 at 2:32pm UTC
okay,
How many characters are in a certain string?
or
How many characters are in the whole array?
Jul 26, 2013 at 2:35pm UTC
if your for loop is not in a function that takes the array as an argument, you can use
sizeof (a)/sizeof (a[0])
Jul 26, 2013 at 2:36pm UTC
Are you talking about counting letters in a string that's
in an array?
Or are you talking about counting characters in a string?
If so, here's an example code:
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
#include <string>
int main()
{
int iLength;
std::string something("Hello" );
iLength = something.length();
std::cout << "There are: " << iLength << " Characters in " << something << std::endl;
return 0;
}
Jul 26, 2013 at 2:48pm UTC
How many characters are in a string.
Maybe I misunderstood the meaning of an array.
I thought this was considered working using an array:
1 2 3 4
string word;
string char2;
// Some code for user input
char1 = word[1];
Jul 26, 2013 at 2:51pm UTC
I am not sure what to put for the condition.
C strings are null terminated.
So you need to loop for the null char '\0'
Andy
Last edited on Jul 26, 2013 at 3:38pm UTC
Jul 26, 2013 at 3:00pm UTC
Maybe I was using the wrong approach.
I think using word.length();
will solve my problem.
Thank you!
Jul 26, 2013 at 3:05pm UTC
1 2 3 4
string word;
string char2;
// Some code for user input
char1 = word[1];
First let me show you how to make an array. Basically an array is a group of datatypes put together. So editing your last code.
1 2 3 4
string word[]; // Makes an array of strings.
string char2;
//some code for user input
char1 = word[1];
I usually make a constant for the number of elements I want in the array. So to answer your first question.
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>
using namespace std;
int main()
{
const int arrayLength = 5; //size of the array.
string words[arrayLength] = {"Bill Gates" , "Steve Jobs" , "Bjarne Stroustrup" , "cppprogrammer297" ,"Hertz" }; //an array of strings with arrayLength number of elemtents.
for (int i = 0; i < arrayLength ; i++)
{
cout << words[i] << " has " << words[i].size() << " characters in it \n" ; //loops through the array and gets the size of each string in the current index(i).
}
cout << endl;
}
Jul 26, 2013 at 3:07pm UTC
Thank you, Hertz!
That is what I was looking for.
Jul 26, 2013 at 3:15pm UTC
you know if you use vectors it allows for more size control, memory management, and you can just use vector::size();
Jul 26, 2013 at 3:20pm UTC
Okay, I will try that to, DTSCode.
Thank you!
Topic archived. No new replies allowed.