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?
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}");
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.
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']);
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);
}
#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);
}
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With