如何获得子用C [英] How to get substring in C

查看:125
本文介绍了如何获得子用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,让我们说THESTRINGHASNOSPACES
我需要的东西,得到的4个字符的字符串从字符串。在第一次电话,我应该得到泰晤士报在第二,我应该得到TRIN。第三,我应该得到GHAS我该怎么办,在C?

I have a string, let's say "THESTRINGHASNOSPACES" I need something that gets a substring of 4 characters from the string. In the first call, i should get "THES" in the second, I should get "TRIN". in the third, I should get "GHAS" how can i do that in C?

推荐答案

如果该任务只复制4个字符,请尝试循环。如果它的将是更先进,你问一个函数,尝试函数strncpy。
<一href=\"http://www.cplusplus.com/reference/clibrary/cstring/strncpy/\">http://www.cplusplus.com/reference/clibrary/cstring/strncpy/

If the task is only copying 4 characters, try for loops. If it's going to be more advanced and you're asking for a function, try strncpy. http://www.cplusplus.com/reference/clibrary/cstring/strncpy/

strncpy(sub1, baseString, 4);
strncpy(sub1, baseString+4, 4);
strncpy(sub1, baseString+8, 4);

for(int i=0; i<4; i++)
    sub1[i] = baseString[i];
sub1[4] = 0;
for(int i=0; i<4; i++)
    sub2[i] = baseString[i+4];
sub2[4] = 0;
for(int i=0; i<4; i++)
    sub3[i] = baseString[i+8];
sub3[4] = 0;

preFER函数strncpy如果可能的话。

Prefer strncpy if possible.

这篇关于如何获得子用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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