【问题标题】:make code to find first integer in string C编写代码以在字符串 C 中查找第一个整数
【发布时间】:2014-03-04 18:01:58
【问题描述】:

你好,我正在做一个软件,它在字符串 1 中搜索字符串 2 中的至少一个字符并打印我们找到的位置。

我的程序中的问题是它打印的值不正确

我的代码 -

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

int main()
{
    char str1[] = "a,s,e,d,8,f";
    char str2[] = "1,2,3,4,5,6,7,8,9,0";
    int i, j, len1, len2, con = 0;

    len1 = strlen(str1);
    len2 = strlen(str2);

    for (i = 0; i < len1; i++)
    {
        for (j = 0; j < len2; j++)
        {
            if (str1[i] == str2[j])
            {
                break;
            }
        }
        con++;
    }
    printf("%d", con);
    system("PAUSE");
}

返回值应该是5,因为8出现在第二个字符串中,位置5

感谢那些能理解问题并帮助我解决问题的人,非常感谢

【问题讨论】:

  • 什么位置?在第一个字符串上还是在第二个字符串上?
  • 第一个字符串中数字 8 的位置
  • 但要注意不是5th,是9th,你没算逗号。
  • 没有。第一个字符串中的第 5 位是 8
  • 我认为 strcspn(str1,"0123456789") 不是可接受的答案?

标签: c string


【解决方案1】:

"break" 只中断内部的 "j" 循环,让外部的 "i" 循环继续运行。有关修复的方法,请参阅此帖子。 How to break out of nested loops?

【讨论】:

  • 你能不能再精确一点,给我需要的破“概念”?
  • 另外,您需要确保以正确的方式计算逗号。如果它们是额外的字符,它们确实会增加长度。您可能只想在声明数组时删除它们。
【解决方案2】:

当您找到正确的字符时,只需在“,”字符和标志“查找”上添加“继续”指令:

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

int main()
    {
    char str1[] = "a,s,e,d,8,f";
    char str2[] = "1,2,3,4,5,6,7,8,9,0";
    int i, j, len1, len2, find = 0, con = 0;

    len1 = strlen(str1);
    len2 = strlen(str2);

    for (i = 0; i < len1; i++)
    {

        if(str1[i]==',')
            continue;

        for (j = 0; j < len2; j++)
        {
            if (str1[i] == str2[j])
            {
                find = 1;
                break;
            }
        }

        con++;

        if(find>0)
            break;

    }
    printf("%d\n", con);

}

【讨论】:

  • 感谢您对我的大力帮助,不胜感激 (:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-19
  • 2019-09-22
  • 1970-01-01
  • 2012-04-25
  • 2022-08-06
  • 1970-01-01
相关资源
最近更新 更多