从没有库函数的句子中分离出单词

时间:2016-10-20 07:14:19

标签: c arrays dynamic-memory-allocation

这里我编写了一个代码,用于在不使用strtok()函数的情况下将单词与给定句子分开。但问题是它只打印第一个单词。为什么其余的单词都不打印?

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

int main ()
{
  char str[] ="This, a sample string.";
  int i=0,k,begin,end;
  while(str[i]!='\0'){
    while(str[i]==' '){
        i++;
    }
    begin = i;
    while(str[i]!=' ' && str[i]!='\0'){
        i++;
    }
    end  = i-1;
    char *ptr =(char *)malloc((end-begin)*sizeof(char));
    for(k=begin;k<=end;k++){
        ptr[k] = str[k];
    }

    printf("%s\n",ptr);
    if(str[i]=='\0'){
        break;
    }
  }
}

5 个答案:

答案 0 :(得分:1)

完整的代码应该是这样的。

我在代码之上更改了代码。

int main ()
{
        char str[] ="This, a sample string.";
        int i=0,k,begin,end;

        int t;

        while(str[i]!='\0'){
                begin = i;
                while(str[i]!=' ' && str[i]!='\0'){
                        i++;
                }
                end  = i-1;

                char *ptr = (char *) malloc( (i-begin)*sizeof(char) + 1);

                t=0;
                for(k=begin;k<=end;k++){
                        ptr[t++] = str[k];
                }
                ptr[t] = '\0';

                puts(ptr);

                if(str[i]=='\0'){
                        break;
                } else
                        while(str[i] == ' ') i++;  //To avoid multiple spaces
        }

        return 0;
}

-Thanks

答案 1 :(得分:1)

您的代码存在问题:

k

ptr被用作strend - begin + 1的索引变量,你应该做的是为ptr使用一个单独的变量,这样它就可以填充0索引中的字符

此外,您没有分配正确的空间。字符数为null character,您还必须为char *ptr =(char *)malloc((end-begin+2)*sizeof(char)); 字符串终止字符)分配空间。

所以正确的分配是:

int index = 0;
for(k = begin;k <= end; k++){
    ptr[jj++] = str[k];
}
ptr[end - begin + 1] = '\0'; 

,您的正确代码是:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div id="TABBEDLOCATEPANEL" ng-show="locate.toggleCheck()" class="container">
<div id=locatePanel class="row">
    <div class="col-md-4 col-sm-3 col-xs-3">
        <div class="tabs-left">
            <ul id=locateTabs class="nav form-tabs nav-pills nav-stacked">
                <li class="active" title="Locate By Address">
                    <a data-toggle="pill" href="#locateTab1" target='_self'><img src="images/Address.png" height="30" width="30"></a>
                </li>
                <li title="Locate By Existing Record">
                    <a data-toggle="pill" href="#locateTab2" target='_self'><img src="images/entity.png" height="30" width="30"></a>
                </li>
                <li title="Locate By Coordinate">
                    <a data-toggle="pill" href="#locateTab3" target='_self'><img src="images/coordinator.png" height="30" width="30"></a>
                </li>
                <li title="Geography" ng-show="locate.getJSON().geographyTab" ng-click="locate.showGeographyData();">
                    <a data-toggle="pill" href="#locateTab4" target='_self'><img src="images/geography.png" height="30" width="30"></a>
                </li>
                <li title="Results" id="ltab5" ng-show="locate.resultsTab">
                    <a data-toggle="pill" href="#locateTab5" target='_self'><img src="images/Result.png" height="30" width="30"></a>
                </li>
            </ul>
        </div>
    </div>
    <div class="col-md-8 col-sm-9 col-xs-9">
        <div class="tab-content">
            <div id="locateTab1" class="tab-pane active">
                <table id=locateAddress style="border-collapse: separate; border-spacing: 5px;">
                    <div class="field-container">
                        <input type='text' class="field" name=locatebyaddress_address ng-model="locate.locatebyaddress_address" required placeholder="Address" init-from-form>
                        <label class="floating-label">Address:</label>
                        <div class="field-underline"></div>
                    </div>
                    <div class="field-container">
                        <input type='text' class="field" name=locatebyaddress_city ng-model="locate.locatebyaddress_city" required placeholder="City" init-from-form>
                        <label class="floating-label">City:</label>
                        <div class="field-underline"></div>
                    </div>
                    <div class="field-container">
                        <input type='text' class="field" name=locatebyaddress_state ng-model="locate.locatebyaddress_state" required placeholder="State" init-from-form>
                        <label class="floating-label">State:</label>
                        <div class="field-underline"></div>
                    </div>
                    <div class="field-container">
                        <input type='text' class="field" name=locatebyaddress_zip ng-model="locate.locatebyaddress_zip" required placeholder="Zip" init-from-form>
                        <label class="floating-label">Zip:</label>
                        <div class="field-underline"></div>
                    </div>
                    <div class="field-container">
                        <input type='text' class="field" name=locatebyaddress_longitude disabled=disabled ng-model="locate.locatebyaddress_longitude" required placeholder="Longitude" init-from-form>
                        <label class="floating-label">Longitude:</label>
                        <div class="field-underline"></div>
                    </div>
                    <div class="field-container">
                        <input type='text' class="field" name=locatebyaddress_latitude disabled=disabled ng-model="locate.locatebyaddress_latitude" required placeholder="Latitude" init-from-form>
                        <label class="floating-label">Latitude:</label>
                        <div class="field-underline"></div>
                    </div>

                </table>
                <br>
                <input type=submit value=Find id=locateByAddress ng-click="locate.locateByAddress();">&nbsp;&nbsp;&nbsp;
                <input type=button ng-click="locate.zoomToLocation();" ng-disabled="locate.entityDisabledCheck" ng-class="{'disabledButton':locate.isDisabledActive}" value="Zoom" id=zoomtolocation>&nbsp;&nbsp;&nbsp;
                <input type=reset value=Cancel ng-click="locate.destroyLocatePanel();" id=cancelLocate>
            </div>
            <div id="locateTab2" class="tab-pane">
                <table id=locateRecord style="border-collapse: separate; border-spacing: 5px;">
                    <tr>
                        <td>Entity Type</td>
                        <td>
                            <select id=locateEntityType ng-change="locate.entityChanged();" ng-model="locate.entityType">
                                <option></option>
                                <option ng-repeat="(key, value) in locate.getJSON().dropdown" value="{{key}}">{{ value }}</option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td>Record Number</td>
                        <td>
                            <input id=recordNumberExistingRecord ng-model="locate.recordNumber" type=text name=recordNumber>
                        </td>
                    </tr>
                </table>
                <br>
                <input type=submit value=Find id=locateByExistingRecord ng-click="locate.getLocationByEntity();">&nbsp;&nbsp;&nbsp;
                <input type=button ng-click="locate.zoomToLocation();" ng-disabled="locate.entityDisabledCheck" ng-class="{'disabledButton':locate.isDisabledActive}" value="Zoom" id=zoomtolocation> &nbsp;&nbsp;&nbsp;
                <input type=reset value=Cancel ng-click="locate.destroyLocatePanel();" id=cancelLocate>
            </div>
            <div id="locateTab3" class="tab-pane">
                <table id=locateCoordinates style="border-collapse: separate; border-spacing: 5px;">
                    <tr>
                        <td>Longitude</td>
                        <td>
                            <input type=text ng-model=locate.locateByCoordinatelongitude>
                        </td>
                    </tr>
                    <tr>
                        <td>Latitude</td>
                        <td>
                            <input type=text ng-model=locate.locateByCoordinatelatitude>
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>
                            <input type=button ng-click="locate.pickCoordinate();" id=coordinatePick name=locatePick value=PICK>
                        </td>
                    </tr>
                </table>
                <br>
                <input type=submit value=Find id=locateByCoordinate ng-click="locate.locateByCoordinate();">&nbsp;&nbsp;&nbsp;
                <input type=button ng-click="locate.zoomToLocation();" ng-disabled="locate.entityDisabledCheck" ng-class="{'disabledButton':locate.isDisabledActive}" value="Zoom" id=zoomtolocation> &nbsp;&nbsp;&nbsp;
                <input type=reset value=Cancel ng-click="locate.destroyLocatePanel();" id=cancelLocate>&nbsp;&nbsp;&nbsp;
                <input type=button ng-click="locate.streetView();" ng-show="locate.streetViewCheck" value="Street View" id=streetView>
            </div>
            <div id="locateTab4" class="tab-pane" ng-show="locate.getJSON().geographyTab">
                <div ng-html-compile="locate.getGeographyHTML()" | trust></div>
            </div>
            <div id="locateTab5" class="tab-pane" ng-show="locate.resultsTab">
                <ul class="listAddress">
                    <li ng-repeat="list in locate.addressList" ng-click="locate.addressListClick($index);">
                        {{ list.formatted_address }}
                    </li>
                </ul>
            </div>
            <!-- /result tab -->
        </div>
        <!-- /tab-content -->
    </div>
    <!-- /tabbable -->
</div>
<!-- /col -->
</div>
<!-- /row -->
</div>
<!-- /container -->

答案 2 :(得分:0)

如果允许您就地修改字符串,则可以执行类似

的操作
#include <stdio.h>

static void print_words(char *str) {
  char *start = str;  // Word start pointer.
  for(;*str;str++) {  // While there are characters...
    if(*str == ' ') {  // Space found!
      *str = '\0';  // Replace the space with a null to end the string
      printf("%s\n", start);  // Output the now null-delimited string
      *str = ' ';  // Return the string to its original form
      start = str + 1;  // Advance the word-start pointer
    }
  }
  printf("%s\n", start);  // Print the last word remaining unprinted, if any
}

int main()
{
  char str[] = "This, a sample string.";
  print_words(str);
}

答案 3 :(得分:0)

您错过了代码中的一些逻辑。

  1. 默认情况下,您正在遍历第二个字。这不是你的要求。

  2. 此块标识来自给定字符串的单词。

  3. 您的分配比我们需要的少一个字节。 终止字符串需要一个额外的字节。 null char。
  4. ** 4。 ptr [k] = str [k]    这是代码中的漏洞。

    这应该像ptr [0] = str [k]; **

    1. 你错过了递增i值以进一步迭代。
    2. ==================第1点=======================

       while(str[i]!='\0'){
          while(str[i]==' '){     -> this is point no 1. This logic will skip first word
              i++;
          }
      
      =================point 2 ================  
      begin = i;
          while(str[i]!=' ' && str[i]!='\0'){
              i++;
          }
          **end  = i-1;**
      ==========================================
      
          char *ptr =(char *)malloc((end-begin)*sizeof(char));  -> point 3.
      
      point 4 :
      
          for(k=begin;k<=end;k++){
              ptr[k] = str[k];
          }
      
      
          printf("%s\n",ptr);
          if(str[i]=='\0'){
              break;
          } 
      point 5 :
           else 
              i++;
        }
      

      -Thanks

答案 4 :(得分:0)

我找到了问题并提出了解决方案:

1.第一个问题是我没有为*ptr分配正确的值。所以,我使用变量j从当前索引的开头开始

2.我需要null终止每次捕获

ptr[k]='\0';

3.所以我总体上做出的改变如下:

for(k=0,j=begin;k<=end-begin;k++,j++){ // use a variable j to start from the beginning of current index
    ptr[k] = str[j];
}
ptr[k]='\0';

完整代码:

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

int main ()
{
  char str[] ="This,  an sample string.";
  int i=0,j,k,begin,end;
  char *ptr;
  while(str[i]!='\0'){
    while(str[i]==' '){
        i++;
    }
    begin = i;
    while(str[i]!=' ' && str[i]!='\0'){
        i++;
    }
    end  = i-1;
    ptr =(char *)malloc((end-begin)*sizeof(char));

    for(k=0,j=begin;k<=end-begin;k++,j++){ // use a variable j to start from the beginning of current index
        ptr[k] = str[j];
    }
    ptr[k]='\0';

    printf("%s\n",ptr);
    if(str[i]=='\0'){
        break;
    }
  }
}