c#string分割字符串_使用String#split方法在Ruby中分割字符串

c#string分割字符串

Unless user input is a single word or number, that input will need to be split or turned into a list of strings or numbers.

除非用户输入是单个单词或数字,否则将需要将该输入拆分或转换为字符串或数字列表。

For instance, if a program asks for your full name, including middle initial, it will first need to split that input into three separate strings before it can work with your individual first, middle and last name. This is achieved using the String#split method.

例如,如果程序要求您提供全名,包括中间名首字母,那么它首先需要将该输入拆分为三个单独的字符串,然后才能与您的个人名,中间名和姓氏一起使用。 这是使用String#split方法实现的。

String#split如何工作 ( How String#split Works )

In its most basic form, String#split takes a single argument: the field delimiter as a string. This delimiter will be removed from the output and an array of strings split on the delimiter will be returned.

在最基本的形式中, String#split接受一个参数:字段定界符作为字符串。 该定界符将从输出中删除,并将返回在定界符上拆分的字符串数组。

So, in the following example, assuming the user input their name correctly, you should receive a three-element Array from the split.

因此,在下面的示例中,假设用户正确输入了名称,则应该从拆分中收到一个三元素数组


#!/usr/bin/env ruby
print "What is your full name? "
full_name = gets.chomp
name = full_name.split(' ')
puts "Your first name is #{name.first}"
puts "Your last name is #{name.last}"

If we run this program and enter a name, we'll get some expected results. Also, note that name.first and name.last are coincidences. The name variable will be an Array, and those two method calls will be equivalent to name[0] and name[-1] respectively.

如果我们运行该程序并输入名称,将会得到一些预期的结果。 另外,请注意name.firstname.last是巧合。 name变量将是一个Array ,这两个方法调用将分别等效于name [0]name [-1]


$ ruby split.rb
What is your full name? Michael C. Morin
Your first name is Michael
Your last name is Morin

However, String#split is a bit smarter than you'd think. If the argument to String#split is a string, it does indeed use that as the delimiter, but if the argument is a string with a single space (as we used), then it infers that you want to split on any amount of whitespace and that you also want to remove any leading whitespace.

但是, String#split比您想象的要聪明。 如果String#split的参数是一个字符串,它的确将其用作分隔符,但是如果该参数是一个带有单个空格的字符串(如我们所用),则它将推断您希望在任意数量的空格上进行拆分并且您还想删除任何前导空格。

So, if we were to give it some slightly malformed input such as

因此,如果我们要给它一些格式错误的输入,例如


Michael C. Morin

(with extra spaces), then String#split would still do what is expected. However, that's the only special case when you pass a String as the first argument. Regular Expression Delimiters

(带有多余的空格),那么String#split仍会执行预期的操作。 但是,这是当您将String作为第一个参数传递时的唯一特殊情况。 正则表达式分隔符

You can also pass a regular expression as the first argument. Here, String#split becomes a bit more flexible. We can also make our little name splitting code a bit smarter.

您还可以将正则表达式作为第一个参数传递。 在这里, String#split变得更加灵活。 我们还可以使我们的小名拆分代码更加智能。

We don't want the period at the end of the middle initial. We know it's a middle initial, and the database won't want a period there, so we can remove it while we split. When String#split matches a regular expression, it does the same exact thing as if it had just matched a string delimiter: it takes it out of the output and splits it at that point.

我们不希望中间首字母的结尾处有句点。 我们知道这是一个中间名首字母,并且数据库在此不需要句号,因此我们可以在拆分时将其删除。 当String#split匹配正则表达式时,它会执行与刚匹配字符串定界符相同的操作:将其从输出中取出并在那一点进行拆分。

So, we can evolve our example a little bit:

因此,我们可以对示例进行一些改进:


$ cat split.rb
#!/usr/bin/env ruby
print "What is your full name? "
full_name = gets.chomp
name = full_name.split(/\.?\s+/)
puts "Your first name is #{name.first}"
puts "Your middle initial is #{name[1]}"
puts "Your last name is #{name.last}"

默认记录分隔符 ( Default Record Separator )

Ruby is not really big on "special variables" that you might find in languages like Perl, but String#split does use one you need to be aware of. This is the default record separator variable, also known as $;.

Ruby在诸如Perl之类的语言中对“特殊变量”的重视并不大,但是String#split确实使用了您需要注意的一种。 这是默认的记录分隔符变量,也称为$;

It's a global, something you don't often see in Ruby, so if you change it, it might affect other parts of the code—just be sure to change it back when finished.

这是全局的,在Ruby中很少见到,因此,如果您对其进行更改,则可能会影响代码的其他部分-请务必在完成后将其更改回去。

However, all this variable does is act as the default value for the first argument to String#split. By default, this variable seems to be set to nil. However, if String#split's first argument is nil, it will replace it with a single space string.

但是,此变量所做的所有操作均充当String#split的第一个参数的默认值。 默认情况下,此变量似乎设置为nil 。 但是,如果String#split的第一个参数为nil ,它将使用单个空格字符串替换它。

零长度分隔符 ( Zero-Length Delimiters )

If the delimiter passed to String#split is a zero-length string or regular expression, then String#split will act a bit differently. It will remove nothing at all from the original string and split on every character. This essentially turns the string into an array of equal length containing only one-character strings, one for each character in the string.

如果传递给String#split的定界符是零长度字符串或正则表达式,则String#split的行为会有所不同。 它将不会从原始字符串中删除任何内容,并在每个字符上进行分割。 这实际上将字符串转换为长度相等的数组,该数组仅包含一个字符的字符串,该字符串中的每个字符一个。

This can be useful for iterating over the string and was used in pre-1.9.x and pre-1.8.7 (which backported a number of features from 1.9.x) to iterate over characters in a string without worrying about breaking up multi-byte Unicode characters. However, if what you really want to do is iterate over a string, and you're using 1.8.7 or 1.9.x, you should probably use String#each_char instead.

这对于迭代字符串很有用,并且在1.9.x之前和1.8.7之前的版本(它们从1.9.x版本向后移植)中使用,可以迭代字符串中的字符,而不必担心会破坏多字符字节Unicode字符 。 但是,如果您真正想要做的是遍历一个字符串,并且您使用的是1.8.7或1.9.x,则应该改用String#each_char


#!/usr/bin/env ruby
str = "She turned me into a newt!"
str.split('').each do|c|
puts c
end

限制返回数组的长度 ( Limiting The Length of the Returned Array )

So back to our name parsing example, what if someone has a space in their last name? For instance, Dutch surnames can often begin with "van" (meaning "of" or "from").

回到我们的名称解析示例,如果某人的姓氏中有空格怎么办? 例如,荷兰人的姓氏通常可以以“ van”(意为“ of”或“ from”)开头。

We only really want a 3-element array, so we can use the second argument to String#split that we have so far ignored. The second argument is expected to be a Fixnum. If this argument is positive, at most, that many elements will be filled in the array. So in our case, we would want to pass 3 for this argument.

我们只真正想要一个3元素的数组 ,因此我们可以使用String#split的第二个参数,到目前为止,我们已经忽略了它。 第二个参数应该是Fixnum 。 如果此参数为正,则最多将在数组中填充许多元素。 因此,在本例中,我们希望为该参数传递3。


#!/usr/bin/env ruby
print "What is your full name? "
full_name = gets.chomp
name = full_name.split(/\.?\s+/, 3)
puts "Your first name is #{name.first}"
puts "Your middle initial is #{name[1]}"
puts "Your last name is #{name.last}"

If we run this again and give it a Dutch name, it will act as expected.

如果我们再次运行它并给它起一个荷兰语的名字,它将按预期运行。


$ ruby split.rb
What is your full name? Vincent Willem van Gogh
Your first name is Vincent
Your middle initial is Willem
Your last name is van Gogh

However, if this argument is negative (any negative number), then there will be no limit on the number of elements in the output array and any trailing delimiters will appear as zero-length strings at the end of the array.

但是,如果此参数为负(任何负数),则输出数组中的元素数将不受限制,并且任何尾随定界符将在数组末尾显示为零长度字符串。

This is demonstrated in this IRB snippet:

此IRB片段对此进行了演示:


:001 > "this,is,a,test,,,,".split(',', -1)
=> ["this", "is", "a", "test", "", "", "", ""]

翻译自: https://www.thoughtco.com/splitting-strings-2908301

c#string分割字符串

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值