Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Get index of char element in array

Tags:

c++

arrays

char

I need to get number of character in array.

const char myarray[5] = {'0', 'a', 'e', 'f', 'c'}; // Create array of char
int number=0; // Create variable
number = getposition(myarray, 'f'); // Now number equals to 3
number = getposition(myarray, 'z'); // -1, because array doesn't have this char

My task is easy because array don't have repeating characters (for example, it can't be smth like this: {'a', '1', 'f', 'a'}). How can I do it?

like image 998
ghostmansd Avatar asked Oct 24 '11 12:10

ghostmansd


People also ask

How do you find the index of a character in a char array?

var index = -1; char[] x = { 'A', 'B', 'C', 'D' , 'E'}; for(int t = 0; t< x. Length; t++) { if (x[t] == 'E') index = t; } Console. WriteLine($"Index is: {index}");

How do you find the index of a char in a string in c?

Just subtract the string address from what strchr returns: char *string = "qwerty"; char *e; int index; e = strchr(string, 'e'); index = (int)(e - string); Note that the result is zero based, so in above example it will be 2.

Can you index an array with a character?

Is it possible to create in Java an array indexed by letter characters ('a' to 'z') rather than by integers? Of course it is possible. You could do this either like this: char theChar = 'x'; print (a[theChar - 'a']);


1 Answers

A little bit more C++:

 #include <algorithm>

int getposition(const char *array, size_t size, char c)
{
     const char* end = array + size;
     const char* match = std::find(array, end, c);
     return (end == match)? -1 : (match-array);
}

A lot more C++:

template <typename T, size_t N>
int getposition(const T (&array)[N], const T c)
{
     const T* match = std::find(array, array+N, c);
     return (array+N==match)? -1 : std::distance(array, match);
}

Bonus C++11/C++11 update

#include <algorithm>
#include <iterator>

template <typename Range, typename T>
size_t index_of(Range const& range, T const& c) {
    using std::begin;
    using std::end;

    auto b = begin(range), e = end(range);
    auto match = std::find(b, e, c);

    return (e==match)? -1 : std::distance(b, match);
}

Bonus C++17 update

Here, the original question gets direct support in std::string_view:

Live On Coliru

#include <string_view>
using namespace std::string_view_literals;

int main() {
    return "hello"sv.find('e');
}
like image 133
sehe Avatar answered Sep 28 '22 04:09

sehe