[英]Simplest way to print this array
这段代码所做的只是将一个句子分解为单个单词,例如:您输入My name is John
,它返回:
我想知道是否有更好的方法来重写这个?
int main() {
int w_size = 0;
bool check_bool = false;
char l_str[81];
char *ptr_to_word[81];
for (char *res_p = &(l_str[0]); *res_p != '\0'; res_p++) {
if ((*res_p != '.') && (*res_p != ',') && (*res_p != ' ') && (check_bool == false)) {
ptr_to_word[w_size] = res_p;
w_size++;
check_bool = true;
}
if (((*res_p == '.') || (*res_p == ',') || (*res_p == ' ')) && (check_bool == true)) {
check_bool = false;
}
}
if (w_size == 0) {
printf("no solution");
} else {
for (int i = 0; i < w_size; i++) {
char *a = ptr_to_word[i];
while ((*a != ',') && (*a != '.') && (*a != '\0') && (*a != ' ')) {
printf("%c", *a);
a++;
}
printf("\n");
}
}
return 0;
}
以下建议的代码:
现在,建议的代码:(按 chqrlie 编辑)
#include <stdio.h>
#include <string.h>
#define MAX_BUF_LEN 1024
#define MAX_WORDS 100
int main( void )
{
char buffer[ MAX_BUF_LEN ] = {0};
char *words[ MAX_WORDS ] = {NULL};
printf( "%s\n", "Please enter a sentence to be divided into words" );
if( fgets( buffer, sizeof( buffer ), stdin ) )
{
size_t wordCount = 0;
char *token;
token = strtok( buffer, ",. " );
while( wordCount < MAX_WORDS && token )
{
words[ wordCount ] = token;
wordCount++;
token = strtok( NULL, ",. " );
}
for( size_t i = 0; i < wordCount; i++ )
{
printf( "%zu: %s\n\n", i+1, words[i] );
}
}
}
以下是建议代码的典型运行结果:
Please enter a sentence to be divided into words
This is a sentence to be divided into words
1: This
2: is
3: a
4: sentence
5: to
6: be
7: divided
8: into
9: words
如果不需要将单词存储到数组中,可以直接 output :
#include <stdio.h>
#include <string.h>
int main() {
char str[81];
printf("Enter string: ");
if (fgets(str, sizeof str, stdin)) {
int pos = 0, len, index = 1;
for (;;) {
/* skip initial separators */
pos += strspn(str + pos, ",.\n ");
if (str[pos] == '\0')
break;
/* compute the length of the word */
len = strcspn(str + pos, ",.\n ");
printf("%d: %.*s\n", index++, len, str + pos);
pos += len;
}
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.