2017-02-15 41 views
-3

說我有一個很隨意的字符串,如所有的話:C程序中找到一個隨機字符串

"%^&%thank*(^ ^&* you&*^^guys" 

什麼是找到字符串中所有單詞的最有效的方法是什麼?沒有按字符檢查字符串?

在這裏,我寫我怎麼會做這種由於要求

int length(char *c) { 
    int n = 0; 

    while(*(c+n)){ 
     n++; 
    } 
    return n; 
} 

int main(int argc, char *argv[]) { 
    int n; 
    int m=0; 
    int count=1; 

    if(argv[1]==NULL) { 
     printf("%s","error"); 
    } 

    while(argv[count]!=NULL){ 
     n=length(argv[count]); 
     while(m!=n){ 
      if('a'<argv[count][m]<'z'){ 
       //do stuff 
      } 
     } 
     count++; 
    } 

    return 0; 
} 
+2

這不是一個網站轉儲你的家庭作業。請顯示你的嘗試,並描述出了什麼問題。 – Carcigenicate

+0

@Carcigenicate這不是我的家庭作業。我通過逐字地檢查字符串來檢查它是否是字母表。我只是想知道是否有更好的方法來做到這一點。 – woshidashen

+0

「我已經通過字符串逐個字符來完成它」 - >發佈代碼以闡明你的意圖以及如何最好地幫助回答這個問題。 – chux

回答

1

你可以使用strtok(3)解析在多個分隔符的字符串。就隨機字符串開展這項工作而言,您可能需要收集可能發生的所有可能的分隔符。 下面是使用strtok()的非常基本的例子:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main(void) { 
    char str[] = "%^&%thank*(^ ^&* you&*^^guys"; 
    const char *delim = "%^*(& "; 

    char *word = strtok(str, delim); 
    while (word != NULL) { 
     printf("%s\n", word); 
     word = strtok(NULL, delim); 
    } 

    return 0; 
} 

UPDATE:

下面是一個更有用的方法,該方法從str收集分隔符:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <ctype.h> 

#define MAXCHAR 256 

int main(void) { 
    char str[] = "%^&%thank*(^ ^&* you&*^^guys"; 
    int count[MAXCHAR] = {0}; 
    char *word; 
    unsigned char curr; 
    size_t charcount = 0, numbytes = strlen(str); 
    char delim[numbytes+1]; 

    for (size_t i = 0; str[i] != '\0'; i++) { 
     curr = str[i]; 
     if (!isalpha(str[i]) && count[curr] == 0) { 
      delim[charcount++] = str[i]; 
      count[curr] = 1; 
     } 
    } 
    delim[charcount] = '\0'; 

    word = strtok(str, delim); 
    while (word != NULL) { 
     printf("%s\n", word); 
     word = strtok(NULL, delim); 
    } 

    return 0; 
} 

此解決方案使用散列法O(n)僅用於添加獨特的定界符。這是一個可能的解決方案,但逐個角色的方法更有效。這是因爲您需要的只是一個臨時緩衝區,用於存儲正在處理的當前字,一旦看到非字母字符,就終止緩衝區並重新開始。

+0

謝謝,它確實需要一段時間來添加所有的分隔符thol大聲笑。 – woshidashen

+0

@GhostKidYao不是。現在我想到了,你可以簡單地遍歷'str',並將非alpha字符添加到'delim'。然後簡單地使用'delim'和'strtok()'。這是一個非常有效的方法。 – RoadRunner

+0

確實是更好的方法,然後檢查每個字符是否爲字母表 – woshidashen