天之道

享受编程的乐趣。
posts - 118, comments - 7, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

取某字符串的子串

Posted on 2012-08-12 11:45 hoshelly 阅读(212) 评论(0)  编辑 收藏 引用 所属分类: Programming
// s 是字符串 startloc 是开始取的位置   len表示取得子串长度
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void substr(char *s, int startloc,int len)
{
    if((startloc < 0) || (startloc >= strlen(s)) || (len<0))
    {
        printf("input error!");
        exit(0);
    }
    int i,c=0;
    char sstr[80];
    while(*s !='\0')
    {
        if(c!=startloc)
        {
            ++c;
            s++;
        }
        else
        {
            for(i=0;i<len;i++)
            {
                sstr[i]= *s;
                s++;
            }
            sstr[i]='\0';
            break;
        }
    }
    printf("%s",sstr);
}

int main()
{
    char str[80];
    int s,l;
    printf("Input string: ");
    gets(str);
    printf("Start Location: ");
    scanf("%d",&s);
    printf("Substring length: ");
    scanf("%d",&l);
    substr(str,s,l);
    return 0;
}

    

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理