繁体   English   中英

从C中的字符串剪切子字符串

[英]Cut substring from a String in C

我有一个字符串(例如"one two three four" )。 我知道我需要剪切从4th 6th符号到6th符号的单词。 我该如何实现?

结果应为:

Cut string is "two"
Result string is "one three four"

目前,我已经实现了删除该词的能力-

for(i = 0; i < stringLength; ++i) { 
          if((i>=wordStart) && (i<=wordEnd))
          {
              deletedWord[j] = sentence[i];
              deletedWord[j+1] = '\0';
              j++;                
          }
    }

但是当我填满sentence[i] = '\\0'我在中间截断字符串时遇到了问题。

与其将'\\0'放在字符串的中间(实际上是终止该字符串), 而是将单词以外的所有内容复制到一个临时字符串,然后再将该临时字符串复制回原始字符串以覆盖它。

char temp[64] = { '\0' };  /* Adjust the length as needed */

memcpy(temp, sentence, wordStart);
memcpy(temp + wordStart, sentence + wordEnd, stringLength - wordEnd);
strcpy(sentence, temp);

编辑:使用memmove (如建议),您实际上只需要一个呼叫:

/* +1 at end to copy the terminating '\0' */
memmove(sentence + wordStart, sentence + wordEnd, stringLengt - wordEnd + 1);

当您将字符设置为“ \\ 0”时,表示正在终止字符串。

您想要做的就是用所需的数据创建一个全新的字符串,或者,如果您确切地知道字符串的来源以及以后如何使用它,则用其余的字符串覆盖剪切词。

/*sample initialization*/
char sentence[100] = "one two three four";

char deleted_word[100];
char cut_offset = 4;
int cut_len = 3;

/* actual code */
if ( cut_offset < strlen(sentence) && cut_offset + cut_len <= strlen(sentence) )
{
    strncpy( deleted_word, sentence+cut_offset, cut_len);
    deleted_word[cut_len]=0;

    strcpy( sentence + cut_offset, sentence + cut_offset + cut_len);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM