I was given a question with two parts. Part A was to reverse the words within a string via string manipulation, for which I used strcpy and strcat. For part B, however, I must reverse the words using pointers. Now I have the code displayed below. Am I on the right track?
The thought behind my function is that I have the original string string1
and I have a pointer at a starting character, then iterate through the string till I hit a white space, giving me the size of the word. Then I place that word at the end of my new string.
Code:
partb(char * string1, int s)
{
int i=0, j=0, k=0, count=0;
char temp[100]={0}, *sp=string1;
for(i=0; i<=s; i++)
{
if(isalnum(string1[i]))
{
k=i;
break;
}
break;
}
for(i=0; i<=s; i++)
{
if(isalnum(string1[i]))
{
count++;
}
else if(string1[i] == ' ')
{
for(j=0; j<=count; j++)
{
}
}
}
}
A few observations:
How do you know that temp
is going to be big enough to store the reversed string? You should allocate a char *
that has the same size as the input string.
Why do you test string1[i] == ' '
when you know that isalnum(string1[i])
is false? You're already at a word break, so the test is unnecessary.
You have forgotten to initialize count
to 0 inside the loop. You must reset count
each time you come upon a new word.
After fixing the errors you can implement the function with your proposed approach, but I'd like to suggest another way. Instead of using count
, you can have a pair of indices a
and b
that traverse a word in opposite directions.
This program demonstrates my approach:
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
int isWordCharacter(char c) {
return isalnum(c);
}
char * reverseWords(char *s) {
int pos = 0, seek, a, b, len;
for (len = 0; s[len] != 0; ++len) { // Find the string length ourselves to
} // avoid using anything from string.h.
char *result = malloc(len * sizeof(char));
while (1) {
while (!isWordCharacter(s[pos])) { // Look for the start of a word.
result[pos] = s[pos];
if (pos == len) { // Are we at the end of the string?
return result;
}
++pos;
}
for (seek = pos + 1; isWordCharacter(s[seek]); ++seek) {
} // Look for the end of the word.
for (a = pos, b = seek - 1; a < seek; ++a, --b) {
result[b] = s[a]; // Scan the word in both directions.
}
pos = seek; // Jump to the end of the word.
}
}
int main() {
char *s = "Hello, world. Today is September 20, 2015.";
printf("%s\n%s\n", s, reverseWords(s));
}
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.