【问题标题】:Reverse words in string using pointers使用指针反转字符串中的单词
【发布时间】:2015-09-20 11:58:53
【问题描述】:

我收到了一个包含两个部分的问题。 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++)
         {

         }  
      }
    }
 }

【问题讨论】:

  • 去一个直到你撞到墙,然后回来问如何继续。
  • "Part A ... 我使用了strcpystrcat" 是否不允许使用指针算法定义您的strcpystrcat 版本?也就是说,是否允许将 B 部分简化为 A 部分?
  • @AndrewRicci 感谢您接受我的回答。你也介意点赞吗?

标签: c string algorithm pointers


【解决方案1】:

一些观察:

  • 你怎么知道temp 会大到足以存储反转的字符串?您应该分配一个与输入字符串大小相同的char *

  • 既然知道isalnum(string1[i]) 是假的,为什么还要测试string1[i] == ' '?你已经在断字了,所以不需要测试了。

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

修复错误后,您可以使用建议的方法实现该功能,但我想建议另一种方法。您可以使用一对索引ab,而不是使用count,它们在相反的方向上遍历一个单词。

这个程序演示了我的方法:

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

【讨论】:

  • 你可以使用库&lt;ctype.h&gt;,然后使用函数isalnum( char c )做同样的事情isWordCharacter( char c )
  • 好点。我会在 isWordCharacter 中这样做以保持通用性。
猜你喜欢
  • 2018-05-02
  • 2012-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多