모든 공백을 제거하는 루비 기능?
모든 공백을 제거하는 루비 기능은 무엇입니까?PHP와 같은 것을 찾고 있습니다.trim()
?
(PHP의 트림과 같은) 선행 및 후행 공백만 제거하려면.strip
, 그러나 모든 공백을 제거하려면.gsub(/\s+/, "")
대신.
s = "I have white space".delete(' ')
그리고 PHP의 에뮬레이션trim()
기능:
s = " I have leading and trailing white space ".strip
String#strip
- 시작과 끝의 공백을 모두 제거합니다.
String#lstrip
- 처음부터요.
String#rstrip
- 끝에서부터요.
String#chomp
(인수 없음) - 행 구분 기호(\n
또는\r\n
)을 클릭합니다.
String#chop
- 마지막 문자를 삭제합니다.
String#delete
-x.delete(" \t\r\n")
- 나열된 공백을 모두 삭제합니다.
String#gsub
-x.gsub(/[[:space:]]/, '')
- 유니코드 1을 포함한 모든 공백을 제거합니다.
주의: 위의 모든 메서드는 원본 문자열을 변환하는 대신 새 문자열을 반환합니다.스트링을 변경할 경우 대응하는 메서드를 호출합니다.!
마지막에.
관련 답변:
" clean up my edges ".strip
돌아온다
"clean up my edges"
Rails/ActiveSupport를 사용하는 경우squish
방법.문자열 양 끝에 있는 공백을 제거하고 여러 공백을 단일 공간으로 그룹화합니다.
예를 들면.
" a b c ".squish
다음과 같은 결과가 됩니다.
"a b c"
api.rubyonrails.org 에서 이 레퍼런스를 확인해 주세요.
"1232 23 2 23 232 232".delete(' ')
=> "123223223232232"
삭제가 더 빨리 진행됩니다 =
user system total real
gsub, s 0.180000 0.010000 0.190000 (0.193014)
gsub, s+ 0.200000 0.000000 0.200000 (0.196408)
gsub, space 0.220000 0.000000 0.220000 (0.222711)
gsub, join 0.200000 0.000000 0.200000 (0.193478)
delete 0.040000 0.000000 0.040000 (0.045157)
루비즈.strip
method는 다음과 같은 PHP를 수행합니다.trim()
.
모든 공백을 제거하려면:
" leading trailing ".squeeze(' ').strip
=> "leading trailing"
@Tass는 나의 원래 답변이 연속적으로 중복된 글자를 삭제한다는 것을 알게 해주었다.-YUK! 그 후, 나는 Rails 프레임워크를 사용하면 이러한 상황에 보다 스마트하게 대처할 수 있는 스퀴시 방식으로 전환했다.
require 'active_support/all'
" leading trailing ".squish
=> "leading trailing"
" good men ".squish
=> "good men"
인용: http://apidock.com/rails/String/squish
조금 늦었지만, 이 페이지를 검색하시는 분은 이 버전에 관심이 있을 것입니다.
사용자가 어떤 식으로든 앱에 잘라 붙여넣은 미리 포맷된 텍스트 덩어리를 정리하고 단어 간격을 유지하려면 다음과 같이 하십시오.
content = " a big nasty chunk of something
that's been pasted from a webpage or something and looks
like this
"
content.gsub(/\s+/, " ").strip
#=> "a big nasty chunk of something that's been pasted from a webpage or something and looks like this"
양쪽에 있는 공백을 제거하려면:
php's trim()과 비슷합니다.
" Hello ".strip
모든 공백을 제거하려면:
" He llo ".gsub(/ /, "")
모든 공백을 제거하려면:
" He\tllo ".gsub(/\s/, "")
" Raheem Shaik ".strip
좌우 사이드 스페이스를 제거합니다.이 코드는 다음을 제공합니다."Raheem Shaik"
split.join
스트링의 모든 공간을 날려버립니다.
" a b c d ".split.join
> "abcd"
타이핑과 기억은 간단하기 때문에 콘솔이나 빠른 해킹에 적합합니다.심각한 코드에서는 환영받지 못하지만 의도를 가리고 있다.
(상기 Justicle의 답변 중 Piotr의 코멘트를 기반으로 합니다.)
또한 다음 사항도 잊지 말아 주세요.
$ s = " I have white space ".split
=> ["I", "have", "white", "space"]
시험해 볼 수 있다
"Some Special Text Values".gsub(/[[:space:]]+/, "")
:space: 를 사용하면 일반 공간과 함께 중단되지 않는 공간을 제거할 수 있습니다.
gsub 또는 delete를 사용합니다.차이점은 gsub은 탭을 삭제할 수 있지만 삭제할 수 없다는 것입니다.편집자가 추가한 파일에 탭이 있는 경우가 있습니다.
a = "\tI have some whitespaces.\t"
a.gsub!(/\s/, '') #=> "Ihavesomewhitespaces."
a.gsub!(/ /, '') #=> "\tIhavesomewhitespaces.\t"
a.delete!(" ") #=> "\tIhavesomewhitespaces.\t"
a.delete!("/\s/") #=> "\tIhavesomewhitespaces.\t"
a.delete!('/\s/') #=> using single quote is unexpected, and you'll get "\tI have ome whitepace.\t"
할 수 있습니다.gsub 에는 문제가 없습니다
할 수 .gsub 메서드는 과 같습니다
a = "this is a string"
a = a.gsub(" ","")
puts a
#Output: thisisastring
gsub 메서드는 첫 번째 인수가 발생할 때마다 검색하여 두 번째 인수로 대체합니다.이 경우 문자열 내의 모든 공간을 대체하고 삭제합니다.
또 다른 예는 다음과 같습니다.
b = "the white fox has a torn tail"
모든 문자 "t"를 대문자 "T"로 바꿉니다.
b = b.gsub("t","T")
puts b
#Output: The whiTe fox has a Torn Tail
여기에서는 많은 제안이 효과가 있지만, 당신의 질문과 "모든 여백 제거"라는 구체적인 대사를 읽었을 때, 제 머릿속에 떠오른 것은 다음과 같습니다.
" a b c " => "abc"
만약 이것이 정말로 필요한 것이라면, 이 간단한 조작을 실시할 수 있습니다.
wide_string = " a b c "
narrow_string = wide_string.delete(" ")
# you can pass all the different kinds
# of whitespaces that you want to remove
puts narrow_string # => "abc"
"asd sda sda sd".gsub(' ', '')
=> "asdsdasdasd"
trim
「」, 「」를 사용하는 입니다.String#strip
다음과 같이 합니다.
string = " Many have tried; many have failed! "
puts "Original [#{string}]:#{string.length}"
new_string = string.strip
puts "Updated [#{new_string}]:#{new_string.length}"
라는 에디트-in-place .String.strip!
('! ')이렇게 하면 문자열 복사본을 만들 필요가 없으며 다음과 같은 경우에 훨씬 더 빠를 수 있습니다.
string = " Many have tried; many have failed! "
puts "Original [#{string}]:#{string.length}"
string.strip!
puts "Updated [#{string}]:#{string.length}"
두 버전 모두 다음 출력을 생성합니다.
Original [ Many have tried; many have failed! ]:40
Updated [Many have tried; many have failed!]:34
는 '아까부터'의 .strip
★★★★★★★★★★★★★★★★★」strip!
그 에 다른 것도 있습니다.츠키다
require 'benchmark'
string = 'asdfghjkl'
Times = 25_000
a = Times.times.map {|n| spaces = ' ' * (1+n/4); "#{spaces}#{spaces}#{string}#{spaces}" }
b = Times.times.map {|n| spaces = ' ' * (1+n/4); "#{spaces}#{spaces}#{string}#{spaces}" }
c = Times.times.map {|n| spaces = ' ' * (1+n/4); "#{spaces}#{spaces}#{string}#{spaces}" }
d = Times.times.map {|n| spaces = ' ' * (1+n/4); "#{spaces}#{spaces}#{string}#{spaces}" }
puts RUBY_DESCRIPTION
puts "============================================================"
puts "Running tests for trimming strings"
Benchmark.bm(20) do |x|
x.report("s.strip:") { a.each {|s| s = s.strip } }
x.report("s.rstrip.lstrip:") { a.each {|s| s = s.rstrip.lstrip } }
x.report("s.gsub:") { a.each {|s| s = s.gsub(/^\s+|\s+$/, "") } }
x.report("s.sub.sub:") { a.each {|s| s = s.sub(/^\s+/, "").sub(/\s+$/, "") } }
x.report("s.strip!") { a.each {|s| s.strip! } }
x.report("s.rstrip!.lstrip!:") { b.each {|s| s.rstrip! ; s.lstrip! } }
x.report("s.gsub!:") { c.each {|s| s.gsub!(/^\s+|\s+$/, "") } }
x.report("s.sub!.sub!:") { d.each {|s| s.sub!(/^\s+/, "") ; s.sub!(/\s+$/, "") } }
end
결과는 다음과 같습니다.
ruby 2.2.5p319 (2016-04-26 revision 54774) [x86_64-darwin14]
============================================================
Running tests for trimming strings
user system total real
s.strip: 2.690000 0.320000 3.010000 ( 4.048079)
s.rstrip.lstrip: 2.790000 0.060000 2.850000 ( 3.110281)
s.gsub: 13.060000 5.800000 18.860000 ( 19.264533)
s.sub.sub: 9.880000 4.910000 14.790000 ( 14.945006)
s.strip! 2.750000 0.080000 2.830000 ( 2.960402)
s.rstrip!.lstrip!: 2.670000 0.320000 2.990000 ( 3.221094)
s.gsub!: 13.410000 6.490000 19.900000 ( 20.392547)
s.sub!.sub!: 10.260000 5.680000 15.940000 ( 16.411131)
가 개인적으로 하는 방법은 '어느 정도'라는 방법을 사용하는 입니다..tr
예를 들어 다음과 같습니다.
string = "this is a string to smash together"
string.tr(' ', '') # => "thisisastringtosmashtogether"
@FrankScmitt가 지적한 바와 같이 공백(스페이스뿐 아니라)을 모두 삭제해야 합니다.
string = "this is a string with tabs\t and a \nnewline"
string.tr(" \n\t", '') # => "thisisastringwithtabsandanewline"
뷰에서 레코드 "제목"을 ID로 사용하려고 했는데 제목에 공백이 있습니다.
솔루션은 다음과 같습니다.
record.value.delete(' ') # Foo Bar -> FooBar
게임 시작은 조금 늦었지만, 후행과 선행 화이트스페이스는strip!
나처럼 어레이가 있는 경우 어레이를 반복하여 인스턴스가 종료된 후 저장해야 합니다.★★★★★★★★★★★★★★★★★★★★★!이렇게 하면 첫 번째 선행 또는 마지막 후행뿐만 아니라 끝 또는 첫 번째에 있는 모든 공백이 제거되었습니다.
예를 들어 다음과 같습니다.
array = ["hello "," Melanie", "is", " new ", "to ", " programming"]
array.each do |i|
i.strip!
end
출력은 ["hello", "Melanie", "is", "new", "to", "programming"입니다.이 코드를 강조 표시하기 위해 만든 비디오에서 이와 유사한 질문을 더 자세히 살펴보고 공유했습니다.
프로그래밍은 처음이라 루프가 종료된 후 스트립을 어레이에 저장하지 않아 사용할 수 없었습니다.
저는 다음과 같은 것을 사용합니다.
my_string = "Foo bar\nbaz quux"
my_string.split.join
=> "Foobarbazquux"
비즈 ruby.scan()
★★★★★★★★★★★★★★★★★」.join()
String 메서드는 문자열의 공백을 극복하는 데도 도움이 됩니다.
scan(/\w+/).join
에 참여합니다.
string = "White spaces in me".scan(/\w+/).join
=>"Whitespacesinme"
또한 문자열의 왼쪽과 오른쪽 부분에서도 공간을 제거합니다.: ★★ltrim
,rtrim
★★★★★★★★★★★★★★★★★」trim
혹시나 이력이 있는 분이 계실까 봐C
,FoxPro
★★★★★★★★★★★★★★★★★」Visual Basic
Ruby
.
2.1.6 :002 > string = " White spaces in me ".scan(/\w+/).join => "Whitespacesinme" 2.1.6 :003 > string = " White spaces in me".scan(/\w+/).join => "Whitespacesinme" 2.1.6 :004 > string = "White spaces in me ".scan(/\w+/).join => "Whitespacesinme" 2.1.6 :005 >
음, 사실 이것을 읽기 위한 더 짧고 쉬운 방법이 있습니다.
그냥 쪼개서 가입하는 게 어때?
"s t r i n g".split(" ").join()
다음과 같이 시험해 보십시오.
"ab c d efg hi ".split.map(&:strip)
이 정보를 얻으려면:
["ab, "c", "d", "efg", "hi"]
1개의 스트링을 사용하고 싶은 경우는, 다음의 명령어를 사용합니다.
"ab c d efg hi ".split.join
언급URL : https://stackoverflow.com/questions/1634750/ruby-function-to-remove-all-white-spaces
'itsource' 카테고리의 다른 글
NSString에서 번호를 제외한 모든 번호 삭제 (0) | 2023.04.12 |
---|---|
sql server 연결 문자열의 "연결 시간 초과"란 무엇입니까? (0) | 2023.04.12 |
MonoTouch와 Objective-C 중 하나를 결정하는 방법 (0) | 2023.04.12 |
Git에서 현재의 지점명을 취득하려면 어떻게 해야 하나요? (0) | 2023.04.12 |
Bash 텍스트 파일에서 배열 생성 (0) | 2023.04.12 |