简体   繁体   English

如何在字符串中从头到尾移动char

[英]how to move char in a string from beginning to an end

As the title says, in my program I (after many procedures) get tokenized words. 正如标题所说,在我的程序中,我(在许多程序之后)获得了标记化的单词。 Unfortunately due to reversing them they hold punctuation characters at the beginning of a word eg. 不幸的是,由于它们被反转,它们在一个单词的开头保留标点字符,例如。 ,moose ,驼鹿

How to move that , from the beginning to the end -> moose, 如何移动,从开始到结束 - >驼鹿,

Up to now I've tried( ptr is char * ): 到目前为止我已经尝试过了( ptrchar * ):

temp = strdup(ptr);
temp = &ptr[0];
ptr[0] = ptr[1];
ptr[strlen(ptr)-1] = temp;
free(temp);

But that gives me errors: 但这给了我错误:

assignment makes pointer from integer without a cast 赋值从整数中生成没有强制转换的指针

warning: assignment makes integer from pointer without a cast 警告:赋值从指针生成整数而没有强制转换

How to fix that? 如何解决?

Something like this: 像这样的东西:

void swap_last(char *str)
{
  const size_t len = strlen(str);
  if(len > 1)
  {
    const char   first = str[0];
    memmove(str, str + 1, len - 1);
    str[len - 1] = first;
  }
}

Note that the above assumes str to be valid. 注意,上面假设str有效。

Generally, the comma should be its own token, so parsing it post-tokenizing is putting a second tokenizer after the first. 通常,逗号应该是它自己的标记,因此在标记化后解析它会在第一个之后放置第二个标记化器。

The best solution is to not just split on white space, but to recognize the comma as it's own token, so you can then test the presence of comma's as part of the grammar. 最好的解决方案不仅仅是拆分空格,而是将逗号识别为自己的标记,这样你就可以测试逗号作为语法的一部分。

Reviewing your code and extrapolating for its lack of types, it's difficult to know the type of your temp variable -- because in some places you're using it like a char * and in others you're using it like a char . 检查你的代码并推断它缺少类型,很难知道你的temp变量的类型 - 因为在某些地方你正在使用它像char *而在其他地方你正在使用它像char

I suspect the compiler error is on line ptr[strlen(ptr)-1] = temp; 我怀疑编译器错误是在行ptr[strlen(ptr)-1] = temp; (because I suspect that temp is a char * ), and the proper fix is: ptr[strlen(ptr)-1] = *temp; (因为我怀疑temp是一个char * ),正确的解决方法是: ptr[strlen(ptr)-1] = *temp;

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

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