【发布时间】:2019-09-15 19:34:25
【问题描述】:
这个程序对用户输入的字符串进行标记,去除多余的空格并将每个单词保存到二维数组中,然后打印标记
示例:
输入: " Hello world string house and car"
输出和预期输出:
token[0]: Hello
token[1]: world
token[2]: string
token[3]: house
token[4]: and
token[5]: car
问题:
问题是我在打印令牌时使用strlen() 函数实现了这一点(代码位于最底部),我不应该使用除stdio.h 和stdlib.h 之外的任何其他库,因为@987654327 @ 函数在 string.h 中定义,我尝试使用 sizeof(arr) / sizeof(arr[0]); 但它不能按我的意愿工作,使用 sizeof 的结果是:
token[0]: Hello
token[1]: world
token[2]: string
token[3]: house
token[4]: and
token[5]: car
�oken[6]: ��
token[7]: �
token[8]: ����
token[9]: �
token[10]:
我希望在不使用 STRLEN() 的情况下获得预期的输出
#include<stdio.h>
#include <stdlib.h>
#define TRUE 1
char tokenize(char *str, char array[10][20])
{
int n = 0, i, j = 0;
for(i = 0; TRUE; i++)//infinite loop until is the end of the string '\0'
{
if(str[i] != ' '){
//position 1, char 1
array[n][j++] = str[i];// if, it is not space, we save the character
}
else{
array[n][j++] = '\0';//end of the first word
n++;// position for next new word
j=0;// start writting char at position 0
}
if(str[i] == '\0')
break;
}
return 0;
}
//removes extra spaces
char* find_word_start(char* str){
/*also removes all extra spaces*/
char *result = (char*) malloc(sizeof(char) *1000);
int c = 0, d = 0;
// no space at beginning
while(str[c] ==' ') {
c++;
}
while(str[c] != '\0'){ // till end of sentence
result[d++] = str[c++]; //take non-space characters
if(str[c]==' ') { // take one space between words
result[d++] = str[c++];
}
while(str[c]==' ') { //
c++;
}
}
result[d-1] = '\0';
//print or return char?
return result;
free(result);
}
int main()
{
char str[]=" Hello world string dudes and dudas ";
//words, and chars in each word
char arr[10][20];
//call the method to tokenize the string
tokenize(find_word_start(str),arr);
int row = sizeof(arr) / sizeof(arr[0]);
/*----------------------------------------------------------------------*/
/*----------------------------------------------------------------------*/
for(int i = 0;i <= strlen(arr);i++)
/*----------------------------------------------------------------------*/
/*----------------------------------------------------------------------*/
printf("token[%d]: %s\n", i, arr[i]);
return 0;
}
【问题讨论】:
-
呈现的代码会产生哪些输出?您可能应该为这两个结果提供代码。不必发布所有代码,只需发布输出循环和使用的变量/数组的声明。您使用
strlen()显示的代码无效,因为arr不是字符串,而是字符串数组。完全不清楚该代码如何产生显示的任何结果。row未使用,我怀疑这段代码与输出无关。 -
strlen 和
sizeof(arr)/sizeof(arr[0])做完全不同的事情。你应该阅读它们。当您了解 strlen 的作用时,您可以轻松实现自己的 strlen 版本并满足要求! -
@clifford 它在一开始就在“示例:”之后,即使用
strlen()的输出,这也是预期的输出,但我不能使用 strlen() 我需要另一个选项. -
好的 - 我明白你在做什么 - 因为你在询问
strlen(),所以你想知道复制到arr的字符串数量。您的两个实现都没有真正起作用 - 您的strlen()解决方案似乎靠运气起作用。将“Hello”替换为“Goodbye”,然后看着它失败!在这种情况下,您实际上不需要数组 或strlen()的长度。这是一个 X-Y 问题——因此会造成混乱。你问的是你的解决方案,而不是你的问题。 -
@BerndElkemann :但事实证明他两个都不想要——他真正需要的是
tokenize()提取的令牌数量。 X-Y question 让一件简单的事情变得复杂
标签: c arrays multidimensional-array