C语言 给定开始和结束索引,如何在 C 中复制部分字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6205195/
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 08:50:03  来源:igfitidea点击:

Given a starting and ending indices, how can I copy part of a string in C?

cstringsubstring

提问by Josh Morrison

In C, how can I copy a string with begin and end indices, so that the string will only be partially copied (from begin index to end index)?

在 C 中,如何复制带有开始和结束索引的字符串,以便仅部分复制字符串(从开始索引到结束索引)?

This would be like 'C string copy' strcpy, but with a begin and an end index.

这就像 'C string copy' strcpy,但有一个开始和一个结束索引。

采纳答案by karlphillip

Have you checked strncpy?

你检查过strncpy吗?

char * strncpy ( char * destination, const char * source, size_t num );

char * strncpy ( char * destination, const char * source, size_t num );

You must realize that beginand endactually defines a numof bytes to be copied from one place to another.

你必须认识到,开始结束实际上定义了一个NUM字节被复制,从一个地方到另一个地方。

回答by Binary Worrier

Use strncpy

使用strncpy

e.g.

例如

strncpy(dest, src + beginIndex, endIndex - beginIndex);

This assumes you've

这假设你已经

  1. Validated that destis large enough.
  2. endIndexis greater than beginIndex
  3. beginIndexis less than strlen(src)
  4. endIndexis less than strlen(src)
  1. 经验证dest足够大。
  2. endIndex大于 beginIndex
  3. beginIndex小于 strlen(src)
  4. endIndex小于 strlen(src)

回答by karlphillip

Just use memcpy.

只需使用memcpy

If the destination isn't big enough, strncpywon't null terminate. if the destination is huge compared to the source, strncpyjust fills the destination with nulls after the string. strncpyis pointless, and unsuitable for copying strings.

如果目的地不够大,strncpy不会空终止。如果目标与源相比很大,则strncpy只会在字符串后用空值填充目标。strncpy毫无意义,不适合复制字符串。

strncpyis like memcpyexcept it fills the destination with nulls once it sees one in the source. It's absolutely useless for string operations. It's for fixed with 0 padded records.

strncpymemcpy类似,只是它一旦在源中看到空值就会用空值填充目标。对于字符串操作绝对没用。它用于修复 0 个填充记录。