给定两个字符串str1和str2,查找str2在str1中出现的位置

给定string str1和string str2,编写一个库函数,返回str2在str1中的位置。

如:str1为"ABCDLANCEXYZ",str2为"LANCE",则返回位置5。如果没有找到,返回-1。(起始位置从1开始)

// findSubStrPosition.c
#include <stdio.h>

int findSubStrPosition(const char *pStr1, const char *pStr2)
{
    int len1 = strlen(pStr1);
    int len2 = strlen(pStr2);
    if (len1 < len2)
        return -1;
    int i = 0;
    for ( ; i < len1; i++)
    {
        int j = 0;
        if (pStr1[i] != pStr2[j])
            continue;
        while(j < len2 & i+j < len1)
        {
            j++;
            if (pStr1[i+j] != pStr2[j])
                break;
        }
        if (j == len2)
            return i+1 ; // start 1
    }
    return -1;
}

int main()
{
    const char *str1 = "ABCDLANCEXYZ";
    const char *str2 = "LANCE";
    int position = 0;
    position = findSubStrPosition(str1, str2);
    printf("the substring position is %d\n", position);
    return 0;
}

// findSubStrPosition.cpp
#include <iostream>
#include <string>

bool isSubstr(std::string str1, std::string str2)
{
    if (str1.length() < str2.length())
        return false;
    int index = 0;
    while(index < str2.length())
    {
        if(str2[index] == str1[index])
            index++;
        else
            return false;
    }
    return true;
}

int findSubStrPosition(std::string str1, std::string str2)
{
    int index = 0;
    while(index < (str1.length() - str2.length()))
    {
        if (isSubstr(str1.substr(index), str2))
            return index + 1;   // start 1
        else
            index++;
    }
    return -1;
}

int main()
{
    std::string str1 = "ABCDLANCEXYZ";
    std::string str2 = "LANCE";
    int position = 0;
    position = findSubStrPosition(str1, str2);
    std::cout<< "the substring position is "<< position << std::endl;
    //std::cout<< "the substring position is "<< str1.find(str2) << std::endl;
    return 0;
}

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值