简体   繁体   中英

Splitting a string in C into separate parts

I've been trying to write a function in C that detects palindromes. 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. 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.

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. 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().

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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