删除字符串C的第一个字符 [英] Remove first char of string C

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

问题描述

我试图删除字符串的第一个字符,并保留剩余部分,我当前的代码不编译和im混淆如何解决它。



我的代码:

  char * newStr(char * charBuffer)
{
int len = strlen(charBuffer);
int i = 1;
char v;
if(charBuffer [0] =='A'|| charBuffer [0] =='Q'){
for(i = 1; i< len; i ++)
v = v + charBuffer [i];
}
v = v +'\0';
return v;
}

Gcc:警告: p>

另外:char * newStr(char * charBuffer)需要保持不变。

解决方案

字符串在C中不会像这样工作。您将缓冲区中的所有字符汇总到 v 变量中。您不能使用+连接。你发布的代码有一些严重的问题,表明有一个理解与如何使用C的差距。



试试这个:

 
char * newStr(char * charBuffer){
int length = strlen(charBuffer);
char * str
if(length< = 1){
str =(char *)malloc(1);
str [0] ='\0';
} else {
str =(char *)malloc(length);
strcpy(str,&charBuffer [1]);
}
return str;
}

或:

 
char * newStr(char * charBuffer){
char * str;
if(strlen(charBuffer)== 0)
str = charBuffer;
else
str = charBuffer + 1;
return str;
}

取决于是否要分配一个新的字符串。您还必须添加用于处理不以Q或A开头的案例的代码。我不包括那些,因为我不知道你在这里想做什么。



确保你做一些研究分配和释放内存malloc和免费。如果你要做C编程,这些是能够使用的基本功能。


Im trying to remove the first char of the string and keep the remainder, my current code doesnt compile and im confused on how to fix it.

My code:

char * newStr (char * charBuffer)
{
    int len = strlen(charBuffer);
    int i = 1;
    char v;
    if(charBuffer[0] == 'A' || charBuffer[0] == 'Q'){
        for(i=1;i<len;i++)
            v = v + charBuffer[i];
    }
    v = v + '\0';
    return v;
}

Gcc: "Warning: return makes pointer from integer without a cast"

Also: "char * newStr (char * charBuffer)" needs to remain the same.

解决方案

Strings don't work like this in C. You're summing up all of the characters in the buffer into the v variable. You can't use + to concatenate. The code you posted has some serious problems which indicate that there's an understanding gap with how to use C.

Try this:

char *newStr (char *charBuffer) {
  int length = strlen(charBuffer);
  char *str;
  if (length <= 1) {
    str = (char *) malloc(1);
    str[0] = '\0';
  } else {
    str = (char *) malloc(length);
    strcpy(str, &charBuffer[1]);
  }
  return str;
}

or this:

char *newStr (char *charBuffer) {
  char *str;
  if (strlen(charBuffer) == 0)
    str = charBuffer;
  else
    str = charBuffer + 1;
  return str;
}

Depending on whether you want to allocate a new string or not. You'll also have to add the code for handling the cases that don't start with 'Q' or 'A'. I didn't include those because I'm not sure exactly what you're trying to do here.

Make sure you do some research into allocating and deallocating memory with malloc and free. These are fundamental functions to be able to use if you're going to be doing C programming.

这篇关于删除字符串C的第一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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