简体   繁体   中英

How to calculate vowel/consonant/characters using for loop react native?

i want to count the number of consonants/vowels/characters depending on the user's given word, then the result is displayed on the screen. I have tried to solve however it still didn't show up

 export default class App extends Component{ constructor(){ super(); this.state ={ value: '', consonant: 0, vowels: 0, characters:0, } } WordAnalyzer = () => { this.setState({value: this.state.value}), () => { const listVowel=['a','i','u','e','o','A','I','U','E','O']; let arr_word= this.state.value.split(''); for (let j=0; j<arr_word.length; j++){ for (let i=0; i< listVowel.length; i++){ if (arr_word[j] == listVowel[i]){ this.setState({vowels: this.state.vowels + 1}); } else{ this.setState({consonant: this.state.consonant +1}); } } this.setState({characters: this.state.characters +1}); } }; } render(){ return( <View style={styles.container}> <Text style={styles.header}>Word Analyzer</Text> <TextInput style= {styles.input} onChangeText={(value) =>this.setState({value})} placeholder='Input a word here' /> <Button color = '#841584' onPress={this.WordAnalyzer} title='Analyze'/> <Text>Word : {this.state.value}</Text> <Text>No of Consonants: {this.state.consonant}</Text> <Text>No of Vowels : {this.state.vowels}</Text> <Text>No of Characters: {this.state.characters}</Text> </View> ); } }

It'd be alot less work (for both you and your computer) if you were to simply use match on the string to figure out how many vowels and consonants are in it.

And, of course, you can simply use this.state.value.length to get the number of characters.

Thus, WordAnalyzer can be refactored into the much simpler:

    WordAnalyzer = () => {
        this.setState({
            characters: this.state.value.length,
            vowels: this.state.value.match(/[AaEeIiOoUu]/g).length,
            consonant: this.state.value.match(/[a-zA-z]/g).length - this.state.value.match(/[AaEeIiOoUu]/g).length
        });
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM