简体   繁体   中英

C++ Char Array Find / Replace a char

So basically I have an array which looks like this:

char array[25];

I have an 'X' put in there, and 24 'O's. I am trying to create a function where I can find the location of 'X' in the array, so then I can move it whenever a control is typed in. Here is some code to get an idea on what I am thinking, I just can't put it together.

int findX(){
    //make this find the location of X out of the 25 char array.
    //then return the slot of X as a number, like if it's in the 20th slot, then  it will return 20 ?
    //return(locationOfX);
}
for(int i = 0; i <= array.Length; i++)
{
    if(array[i] == 'X')
    {
        return i;
    }
}

This should do it, I had no chance testing it, but it should work

Pass in the array and the number of elements.
1. The manual approach:

int findX(char arr[], int count){
    for (int i = 0; i < count; i++){
        if (arr[i] == 'X'){
            return i;
        }
    }
    return -1;
}

2. Use std::find function:

int findX2(char arr[], int count){
    return std::find(arr, arr + count, 'X') - arr;
}

Slight twist with the std::distance function:

int findX2(char arr[], int count){
    return std::distance(arr, std::find(arr, arr + count, 'X'));
}

3. Pass in the beginning and the end of the array:

int findX3(char* arrbegin, char* arrend){
    return std::distance(arrbegin, std::find(arrbegin, arrend, 'X'));
}

and use like:

std::cout << findX3(std::begin(arr), std::end(arr));

4. Template function left as an exercise.
That being said, prefer std::vector or std::array to raw arrays.

我认为 Ron 的答案更正确,因为实际上我认为在 C 中没有像“XXX.length()”这样的函数,因此您需要将数组的长度传递给函数。

In language C you can use strstr function.

#include "string.h"
int findX(char array[])
{
   char *result = strstr(array, "s");
   return result - array;
}
int main()
{
   char array[25];
   int index = findX(array);
}

in C++ use std::find() or just change array to std::string and use string::find

here is the code:

#include <string>

int main()
{
    std::string array = "oooooooooosoooooooooooooo";
    int index = array.find("s");
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM