Ruby字符串中插入空格删除的问题

Python065

Ruby字符串中插入空格删除的问题,第1张

先把字符串转成字符数组,然后写个函数扫一遍字符数组,遇到2的倍数步就加个空格,返回新字符串

字符串转成字符数组:

>>str = "ABC"

=>"ABC"

>>chars = str.scan(/./)

=>["A", "B", "C"]

函数给你个python的参考吧,话说我python居然还真没忘。。。

'''正向操作

def f(x):

s = ""

for i in range(len(x)):

if i % 2 == 0:

s = s + ' '

s = s + x[i]

return s[1:]

'''逆向操作

def f_rev(x):

s = ""

'''凡是偶数位的空格删掉

'''

for i in range(len(x)):

if (i-2) % 3 == 0 and x[i] == ' ':

continue

s += x[i]

return s

'''测试

s = "abcdedg"

print (f_rev(f(s))

不建议使用print函数。使用puts函数即可:

class HelloWorld

def HelloWorld.hello(name = "Ruby")

  puts "Hello,world.I am #{name}."

end

end

HelloWorld.hello("Jone")

HelloWorld.hello