请问在c语言中我想取一个字符串中第二个字符,怎么写

wolfza 2002-09-13 03:24:20
请指教
...全文
870 14 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhk1124 2002-09-14
  • 打赏
  • 举报
回复
//这实践上很简单的不过还是给你设计一个函数让你好用一点
//入口参数 &aa数组地址, b 是想取第几个数
int fun (int &aa,int b )
{
int *p;
p=aa;
b--; //因数组是从0---N, 实际表示是1---(N-1)
return *(p+b);

}
//使用时注意 b 的数据不要出阶
alexxing 2002-09-13
  • 打赏
  • 举报
回复
上面的 mid() 函数如果返回 NULL,表示失败(没办法,有 malloc 就要考虑失败),如果返回的不是 NULL,用完后必须 free
alexxing 2002-09-13
  • 打赏
  • 举报
回复
上面的程序还是有问题,下面这个程序好像是终于“功德圆满”了

const char * mid(const char *str, size_t start, size_t len)
{
size_t totallen = strlen(str);
if ( start >= totallen )
{
start = totallen;
len = 0;
}
else if ( start + len >= totallen )
{
len = totallen - start;
}

char * p = (char *) malloc(len+1);
if ( p )
{
if (len)
memcpy(p, str + start, sizeof(char)*len);
p[len] = 0;
}

return p;
}
alexxing 2002-09-13
  • 打赏
  • 举报
回复
老猫的函数还需要做一点完善,没有考虑 start > len 的情况

// 注意:用完 mid 后,需要 free 返回的字符串
const char * mid(const char *str, size_t start, size_t len)
{
size_t totallen = strlen(str);
if ( start >= totallen )
{
char * p = malloc(1);
p[0] = 0;
}
else
{
if ( start + len >= totallen )
len = totallen - start;
char * p = (char *) malloc(len+1);
memcpy(p, str + start, len);
p[len] = 0;
}
return p;
}
zhaoyang 2002-09-13
  • 打赏
  • 举报
回复
在c中没有mid,你的自己写函数。c++中可以用cstring类。
blh 2002-09-13
  • 打赏
  • 举报
回复
因为我是仿照mid函数的格式,呵呵
Plotto 2002-09-13
  • 打赏
  • 举报
回复
To blh:
Why not use p as an input argument?
blh 2002-09-13
  • 打赏
  • 举报
回复
给你一个例子

char *mid(const char *str, int start, int size)
{
int len;
char *p = NULL;
len = strlne(str);
len = (len > size) ? size : len;
p = malloc(len + 1);
p[len] = 0;
strncpy(p, str + start, len);
return p;
}

记得是用mid返回值后,free内存

black_snail 2002-09-13
  • 打赏
  • 举报
回复
char *p;
char a[4][30]; ?

a[4][30] is a string array like {"abc","dfdfd","dfdf","dfd"}

If you want to declare a string
char a[30];
a[1] is the second char . (a[0] is the first )
greysky123 2002-09-13
  • 打赏
  • 举报
回复
C中没有现成的函数,mid是VC里对CString的操作函数,在C中你只能自己写,给你一个比较简单的写法,如:
char *p;
char a[4][30];
if (strcmp(a[2],"1")==0)
{
p=(a[2])+1;//p指向a[2]中从a[2][1]开始的字符串
if (strcmp(p,"2")==0)
{
}
}
不过,我有个疑问,既然a[2]是字符串"1",那么a[2][1]应该是空的了,也就是p指向的空间为空,那这一步就没有任何意义了;是否将strcmp改为strncmp(a[2],"1",1)更为妥当,也许是我没有理解你的意思

darkelf 2002-09-13
  • 打赏
  • 举报
回复
我错了,我悔过

:(
darkelf 2002-09-13
  • 打赏
  • 举报
回复
老大,你的a[2]只是一个字符啊,你用字符和一个字符串比较,当然不可以啦

应该是
if(strcmp(a[2],'1')==0)才对啊
wolfza 2002-09-13
  • 打赏
  • 举报
回复
有没有什么函数譬如mid 可以使用的,我试过,发现类型不匹配
char *p
char a[4][30]
if strcmp(a[2],"1")==0) //a[2]是 我要截取的字符串
{
p=mid(a[2],2,1)
if (strcmp(p,"2")==0)
{
}
}
Plotto 2002-09-13
  • 打赏
  • 举报
回复
p[1] or *(p+1)

70,019

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧