官术网_书友最值得收藏!

Using the split method

Now let's walk through the split method. The split method is a powerful tool that allows you to split a sentence into an array of words or characters. For example, type the following code:

str = "The quick brown fox jumped over the quick dog"  
p str.split

You'll see that it converts the sentence into an array of words:

This method can be particularly useful for long paragraphs, especially when you want to know the number of words in the paragraph. Since the split method converts the string into an array, you can use all the array methods, like size, to see how many words are in the string.

We can leverage method chaining to find out how many words are in the string, as shown here:

str = "The quick brown fox jumped over the quick dog" 
p str.split.size

This should return a value of 9, which is the number of words in the sentence:

To know the number of letters, we can pass an optional argument to the split method and use the following format:

str = "The quick brown fox jumped over the quick dog" 
p str.split(//).size

If you want to see all of the individual letters, we can remove the size method call, like this:

p str.split(//) 

Your output will now look like this:

Notice that it also includes spaces as individual characters, which may or may not be what you want a program to return.

This method can be quite handy while developing real-world applications. A good practical example of this method is Twitter. Since this social media site restricts users to 140 characters, this method is sure to be a part of the validation code that counts the number of characters in a Tweet.

主站蜘蛛池模板: 平原县| 舒城县| 临猗县| 双牌县| 邛崃市| 贵德县| 玉门市| 乌鲁木齐市| 汤原县| 应用必备| 许昌市| 孝感市| 黔江区| 兴义市| 汾阳市| 徐汇区| 东兰县| 临清市| 广州市| 台中县| 武强县| 托克托县| 山东省| 分宜县| 滨州市| 英德市| 日土县| 景泰县| 盈江县| 全南县| 平度市| 甘泉县| 神农架林区| 萍乡市| 沈阳市| 自贡市| 吉木萨尔县| 鱼台县| 紫金县| 揭西县| 屏南县|