簡體   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