读取字符串的各个字符和字符串本身由字符串数组指向

时间:2014-09-29 23:53:05

标签: c arrays string pointers

  

在下面的代码中,我试图传递字符串数组' char * wordArray [20] ......"进入main函数,用于查找wordArray中包含用户输入字符的所有字符串,并打印每个这样的字符串。功能" findWords"定义为期望一个常量字符串数组,它的长度和用户输入字符,因为该数组将是只读的。根据我使用的文本中的示例,底部是用于从指针到字符串读取单个字符以及从指针数组读取字符串的方法的组合。

#include <stdio.h>
#include <stddef.h>
#include <ctype.h>

int arrLength = 0; // Global variable dec. and initialization


void findWords ( const char *c[], int length, char letter ) {

size_t element = 0;
size_t count = 0;

for (element = 0; element < length; element++) {

    for (count = 0; c[count] != '\0'; count++) {

        if (c[count] == letter) {

            printf("%s", c[element]);

        }

        else {

            printf("%s", c[count]);
        }
    }

    count++;
}

return;

} // End function findWords



int main (void) {

{ // Begin Problem 3

    // step 1: printf "Problem 3"
    puts("Hiya");

    // step 2: create a string array of 3 pointers to strings containing at this point, random  
       words.

    const char *wordArray[3] = { "cake", "foxtrot", "verimax" };


    char usrInp; // Holds user-input letter.

    // step 3: "Input a letter from the user."
    // This do...while loop repeats until the user has entered either a lower- or uppercase    
letter.

    do {

        puts("Please enter one lowercase letter - any you'd like\n"); // One string argument 
calls for output function puts(); rather than printf();

        usrInp = tolower ( getchar() );


    } while ( isalpha (usrInp) == 0 );

    findWords( wordArray, arrLength, usrInp );

} // End Problem 3
} // End function main

2 个答案:

答案 0 :(得分:1)

在findWords:

for (element = 0; element < length; element++) {
    for (count = 0; c[element][count] != '\0'; count++) {
        if (c[element][count] == letter) {
            printf("%s\n", c[element]);
            break;
        }
    }
}

at main:

arrLength = sizeof(wordArray)/sizeof(*wordArray);//arrLength = 3;
findWords( wordArray, arrLength, usrInp );

答案 1 :(得分:0)

c [count]是char *,这意味着你无法将它与char进行比较。这个指针只保存当前字符串的地址。你需要遍历那个字符串才能检查字母 在您的代码中,您需要更改:

if (c[element][count] == letter)