繁体   English   中英

使用指针反转字符串中的单词

[英]Reverse words in string using pointers

我的问题分为两个部分。 A部分是通过字符串操作来反转字符串中的单词,为此我使用了strcpy和strcat。 但是,对于B部分,我必须使用指针来反转单词。 现在,我在下面显示了代码。 我在正确的轨道上吗?

我的功能背后的想法是,我有原始的字符串string1并且在起始字符处有一个指针,然后遍历该字符串,直到找到空白为止,这给了我单词的大小。 然后,将该词放在新字符串的末尾。

码:

 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++)
         {

         }  
      }
    }
 }

一些观察:

  • 您如何知道temp足够大以存储反向字符串? 您应该分配与输入字符串相同大小的char *

  • 当您知道isalnum(string1[i])为假时,为什么string1[i] == ' '测试string1[i] == ' ' 您已经停下来了,所以不需要测试。

  • 您忘记了在循环内将count初始化为0。 每次遇到新单词时,都必须重置count

修复错误后,您可以使用建议的方法来实现该功能,但是我想提出另一种方法。 除了使用count ,还可以使用一对索引ab沿相反的方向遍历一个单词。

该程序演示了我的方法:

#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));
}

暂无
暂无

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

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