3 Replies - 653 Views - Last Post: 18 February 2013 - 06:29 PM Rate Topic: -----

#1 NoRemorse  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 65
  • Joined: 26-January 11

Determine the number of elements in a string array

Posted 18 February 2013 - 01:37 PM

Letīs say that we have string stringArray[5] = {"Lucy","Mary","Tina"}
Is there a way to get the number of names in the array, not the size of the array nor the number of elements there can be in the array max? If there is not such a built-in way,can anyone please give me instructions how could I determine that number? Any help is appreciated.
Is This A Good Question/Topic? 0
  • +

Replies To: Determine the number of elements in a string array

#2 BetaWar  Icon User is offline

  • #include "soul.h"
  • member icon

Reputation: 1184
  • View blog
  • Posts: 7,254
  • Joined: 07-September 06

Re: Determine the number of elements in a string array

Posted 18 February 2013 - 01:48 PM

With a standard array there is no built in way to get the number of elements in it. However, if you are willing to NULL fill the array (or otherwise fill the array with a known non-value) you can loop through it and determine how many of the values are not the known non-value.

For instance:
string stringArray[5] = {"Lucy", "Jill", "Amy", "", ""}; // where "" is the known non-value
int numberOfElements = 0;
for(int i = 0; i < 5; i++){
  if(stringArray[i] == ""){
    numberOfElements++;
  }
}
cout << "Elements: " << numberOfElements << endl;



Hope that helps.
Was This Post Helpful? 1
  • +
  • -

#3 CTphpnwb  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 3077
  • View blog
  • Posts: 10,796
  • Joined: 08-August 08

Re: Determine the number of elements in a string array

Posted 18 February 2013 - 01:51 PM

Since you're using C++ strings, why not use C++ vectors? Then you could just do:
cout << "Elements: " << stringArray.size() << endl;


Was This Post Helpful? 2
  • +
  • -

#4 #define  Icon User is offline

  • Duke of Err
  • member icon

Reputation: 1398
  • View blog
  • Posts: 4,873
  • Joined: 19-February 09

Re: Determine the number of elements in a string array

Posted 18 February 2013 - 06:29 PM

The default constructor creates an empty string so null values should not be required.
Was This Post Helpful? 2
  • +
  • -

Page 1 of 1