Reputation: 823
Splitting a string with a defined delimiter and then using indexes to call the element required is a pretty easy job in python. Specifically, calling the second last element from a list of variable length(since the string given can have a lot of elements after splitting), is a cakewalk because of the simple syntax.
Example:
str = "swscan.apple.com"
str_list = str.split(".")
print(str_list)
print(str_list[-2])
Output of this would be:
['swscan', 'apple', 'com']
apple
But doing the same thing in C is a pretty tedious job. I have to use strtok
function for the same, which is further stored in a pointer value, and is then traversed through, which gives us the elements after splitting.
I am able to achieve this, but the thing that really puts me off is the part where I have to access the second last element of the same. Can somebody help me on how this can be achieved? Here is what I have done so far:
int main()
{
char str[] = "swscan.apple.com";
int init_size = strlen(str);
char delim[] = ".";
char *ptr = strtok(str, delim);
while(ptr != NULL)
{
printf("'%s'\n", ptr);
ptr = strtok(NULL, delim);
}
return 0;
}
The output of this would be:
'swscan'
'apple'
'com'
But this still does not come in a structured format with which I can access the second last element using the indexes. Any help would be appreciated. Thanks in advance.
Upvotes: 4
Views: 702
Reputation: 30489
You can store the last two items in an array and print the second last item.
[...]
char delim[] = ".";
char *lastElement[2] = {0}; /* 1. To store delimited items */
char *ptr = strtok(str, delim);
while(ptr != NULL)
{
lastElement[0] = lastElement[1]; /* 2. Update */
lastElement[1] = ptr;
printf("'%s'\n", ptr);
ptr = strtok(NULL, delim);
}
if(lastElement[0]) { /* 3. Does second last item exist */
printf("%s\n", lastElement[0]); /* 4. Second last item */
}
[...]
This idea can be extended to get any arbitrary element also.
Upvotes: 2