查找字符串是否包含重复项? [英] Finding whether a string contains a duplicate or not?

查看:70
本文介绍了查找字符串是否包含重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我编写的代码,用于查找字符串中的重复项。此代码不起作用。它使用指向字符串的指针。指针*首先指向字符串的第一个元素,第二个指向第二个元素。并且两个指针递增并循环通过字符串并找到重复项。这是它应该如何工作,如果我错了就纠正我?

Here is a code which i wrote to find duplicates in a string . This code doesn't work. It uses pointers to the string . The pointer *first points to first element of the string and *second to second element . And the two pointers increment and loop thrrough the string and find the duplicates .this is how it is supposed to work ,correct me if i am wrong?





#include<stdio.h>
main()
{
char string[]= "hello";
int len=strlen(string);
char *first=string;
char *second=string+1;
while(first <len-1 && second<len)
{
 if(*first==*second)
 {
  printf("A duplicate found\n");
 }
 first++;
 second++;
}
}

推荐答案

嗯。



第一个和第二个都是指针。你正在将它们与整数进行比较?你认为这是个好主意吗?你期望结果是什么?



相反,用for循环替换你的while循环:

Um.

First and second are both pointers. You are comparing them to integers? Do you think this is a good idea? What do you expect the result to be?

Instead, replace your while loop with a for loop:
#include<stdio.h>
main()
      {
      int i;
      char string[]= "hello";
      int len=strlen(string);
      char *first=string;
      char *second=string+1;
      for (i = 0; i < len - 1; i++)
          {
          if(*first==*second)
              {
              printf("A duplicate found\n");
              }
          first++;
          second++;
          }
      }


这篇关于查找字符串是否包含重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆