简体   繁体   English

将C中的字符串拆分为单独的部分

[英]Splitting a string in C into separate parts

I've been trying to write a function in C that detects palindromes. 我一直在尝试用C编写检测回文的函数。 The program currently looks like the following: 该程序当前如下所示:

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

int main()
{
    char palindrome[24]; int palength; int halflength;
    gets(palindrome);
    palength = strlen(palindrome);
    halflength = palength / 2;
    printf("That string is %u characters long.\r\n", palength);
    printf("Half of that is %u.\r\n", halflength);
    return 0;
}

Right now it detects the length of a string, and also shows what half of that is. 现在,它检测字符串的长度,并显示其中一半。 This is just to make sure it is working how I think it should be. 这只是为了确保它按照我的预期工作。 What the rest of the function should do (if possible) is take the integer from "halflength" and use that to take that amount of characters off of the beginning and end of the string and store those in separate strings. 函数的其余部分应该做的(如果可能的话)是从“ halflength”中取一个整数,并使用该整数从字符串的开头和结尾取走一定数量的字符,并将它们存储在单独的字符串中。 From there I'd be able to compare the characters in those, and be able return true or false if the string is indeed a palindrome. 从那里,我可以比较其中的字符,如果字符串确实是回文,则可以返回true或false。

TL;DR - Is it possible take a certain amount of characters (in this case the integer "halflength") off the front and end of a string and store them in separate variables. TL; DR-是否可以从字符串的开头和结尾取走一定数量的字符(在这种情况下为整数“ halflength”),并将它们存储在单独的变量中。 Read above for more information on what I'm trying to do. 阅读以上内容以获取有关我要执行的操作的更多信息。

PS - I know not to use gets(), but didn't feel like writing a function to truncate \\n off of fgets(). PS-我知道不使用gets(),但不想编写一个函数来截断fgets()的\\ n。

int len = strlen(palindrome) - 1; // assuming no \n
int half = len << 1;
for (int i=0; i<=half; ++i)
  if(palindrome[i] != palindrome[len-i])
     return false;
return true;

What if you do something like this, 如果您这样做,该怎么办?

char *str1="lol",*str2;
str2=strrev(str1);

//if both are same then it actually is a palindrome ; //如果两者相同,则实际上是回文; )

Found out I was approaching the problem wrong. 发现我正在错误地处理问题。 How I should be doing this is iterating over the characters using a pointer both backwards and forwards. 我应该怎么做,就是使用向后和向前的指针遍历字符。 Although if you'd still like to answer the original question it could still be useful at some point. 尽管如果您仍然想回答原始问题,它有时还是有用的。

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

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