String help

closed account (jwkNwA7f)
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!
okay,
How many characters are in a certain string?

or

How many characters are in the whole array?
if your for loop is not in a function that takes the array as an argument, you can use
sizeof(a)/sizeof(a[0])
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;
}
closed account (jwkNwA7f)
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];
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
closed account (jwkNwA7f)
Maybe I was using the wrong approach.

I think using word.length(); will solve my problem.

Thank you!
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;

}
closed account (jwkNwA7f)
Thank you, Hertz!

That is what I was looking for.
closed account (Dy7SLyTq)
you know if you use vectors it allows for more size control, memory management, and you can just use vector::size();
closed account (jwkNwA7f)
Okay, I will try that to, DTSCode.

Thank you!
Topic archived. No new replies allowed.