简体   繁体   English

如何在字符串中间找到一个字符?

[英]How to find a character in the middle of a string?

I want to find 3 characters in a string.我想在一个字符串中找到 3 个字符。

I already use strchr and strrchr but I cannot get the middle char.我已经使用strchrstrrchr但我无法获得中间字符。

For example:例如:

hehoho

If I use strchr I get the first h .如果我使用strchr我得到第一个h

If I use strrchr I get the last h .如果我使用strrchr我得到最后一个h

How can I get the the middle h : he h oho ?我怎样才能得到中间的h : he h oho ?

char *p;
char* q;
int loc2;
int loc;
char ch[100];
char s[100] = "heheho"

p = strrchr(s, ch);
q = strchr(s, ch);

loc = (int)(p - s);
loc2 = (int)(q - s);

if ( q != NULL)
{   
    a[loc] = ch;
    a[loc2] = ch;
}

One way is to keep calling strchr until you run out of found characters.一种方法是继续调用strchr直到找到的字符用完。 The function returns NULL when the character isn't found, so maybe something like this:当找不到字符时,function 返回NULL ,所以可能是这样的:

for(const char* ptr=s; ptr!=NULL && *ptr!='\0'; ptr=strchr(ptr+1, key))
{
  index[found_count] = ptr-s;
  found_count++;
}

This stores down the array index of every found character that matches the character "key", then keeps searching until it finds no more matches and strchr returns NULL.这将存储与字符“key”匹配的每个找到的字符的数组索引,然后继续搜索,直到找不到更多匹配项, strchr返回 NULL。 So it finds all occurrences.所以它会找到所有的出现。

Each time you tell strchr to look at the current position + 1. If not for the + 1, you'd keep getting the same result in infinity.每次你告诉strchr查看当前的 position + 1。如果不是 + 1,你会在无穷大中继续得到相同的结果。

The check *ptr!='\0' for null termination isn't really necessary but catches the case of an empty input string.检查 null 终止的*ptr!='\0'并不是真正必要的,但可以捕获空输入字符串的情况。

ptr-s is pointer arithmetic and gives a integer type corresponding to the position in the string. ptr-s是指针算术,给出一个 integer 类型,对应于字符串中的 position。 It will only get executed when the pointer actually points at a valid array item.只有当指针实际指向一个有效的数组项时,它才会被执行。

Full example:完整示例:

#include <stdio.h>
#include <string.h>

int main (void)
{
  const char s[100] = "heheho";
  const char key = 'h';
  int found_count = 0;
  int index[10];

  for(const char* ptr=s; ptr!=NULL && *ptr!='\0'; ptr=strchr(ptr+1, key))
  {
    index[found_count] = ptr-s;
    found_count++;
  }

  for(size_t i=0; i<found_count; i++)
  {
    printf("Found %c at index %d.\n", key, index[i]);
  }

  printf("So the middle one is at index %d.", index[found_count/2]);
}

Output: Output:

Found h at index 0.
Found h at index 2.
Found h at index 4.
So the middle one is at index 2.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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