如何从用C字符串中的给定索引处删除字符? [英] How to remove the character at a given index from a string in C?

查看:186
本文介绍了如何从用C字符串中的给定索引处删除字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何删除从字符串中的字符?

How do I remove a character from a string?

如果我有字符串ABCDEF和我想删除B我该怎么做?

If I have the string "abcdef" and I want to remove "b" how do I do that?

删除第一的性格很容易与此code:

Removing the first character is easy with this code:

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

int main()
{
   char word[] = "abcdef";
   char word2[10];

   strcpy(word2,&word[1]);

   printf("%s\n", word2);

   return 0;
}

strncpy(word2,word,strlen(word)-1);

会给我不会在最后字符字符串,但我还是没弄明白如何在一个字符串的删除字符。

will give me the string without the last character, but I still didn't figure out how to remove a char in the middle of a string.

推荐答案

memmove与能处理重叠的区域,我会尝试这样的事情(未测试,也许+ -1号)

Memmove can handle overlapping areas, I would try something like that (not tested, maybe +-1 issue)

char word[] = "abcdef";  
int idxToDel = 2; 
memmove(&word[idxToDel], &word[idxToDel + 1], strlen(word) - idxToDel);

在ABCDEF

在abdef

这篇关于如何从用C字符串中的给定索引处删除字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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