C语言 如何在c中获取char数组的一部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16807004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:30:02  来源:igfitidea点击:

how to get a part of a char array in c

carrays

提问by dali1985

I am new in C and I have the following simple code. I know that with the strncpy I can copy characters from string.

我是 C 新手,我有以下简单的代码。我知道使用 strncpy 我可以从字符串中复制字符。

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

int main ()
{
  char str1[]= "To be or not to be";
  char str2[40];

  strncpy ( str2, str1, 5 );
  str2[5] = '
To be
'; /* null character manually added */ puts (str2); return 0; }

The output of this code is

这段代码的输出是

  strncpy ( str2, str1+6, 9);
  str2[9] = '
strncpy ( str2, str1+strlen("To be "), strlen("or not to") );
str2[strlen("or not to")] = '
strncpy ( str2, str1 + 6, 9 );
';
'; /* null character manually added */

If I want the result to be ′or not to′ how can I read these characters? From 7-15 in this case?

如果我希望结果是“或不”,我该如何读取这些字符?从 7-15 在这种情况下?

回答by Vijay

Use :

用 :

##代码##

回答by Dayal rai

No need to count manually ,you can use standard library function for this.Try like following

无需手动计数,您可以为此使用标准库函数。尝试如下

##代码##

回答by Bart Friederichs

Simple way to do that, offset str1:

这样做的简单方法,偏移量str1

##代码##