It's not over until you win

[Grasshopper] Fundamental II-1. String Manipulation 본문

IT/Grasshopper

[Grasshopper] Fundamental II-1. String Manipulation

캬옹몽몽이 2019. 1. 22. 18:32

자. 다시 챕터 1을 시작해보자.


2-1-1. Post Climb Postcard


.length property에 대해서 배운다. .length은 string 안의 글자수를 세는 기능을 가지고 있다.

일단 아래의 Code는 주어진 상태에서 시작한다.

앞에서 언급했는지 기억나지 않는데, string은 coding 할 때 letters, words, sentences를 통칭한다. 

var message = pickRandom ( [ 

  'Hello from the top of Code Mountain. The view is amazing. My adventure is just beginning, where to next?',

  'Greetings from Code Mountain.',

  'The view is awesome from way up here at the peak. I can see a whole world of code to explore.',

  'Just climbed a mountain of code and I am ready for more.'

  ] ) ; 


위 메세지가 80글자 미만이면 'The message fits on a postcard.' 라 하고, 아니면 'The message is too long for a postcard.'라고 하라는 예시다.

print (message) ;

if (message.length > 80 ) { print ('The message is too long for a postcard.') ; }

if (message.length < 80 ) { print ('The message fits on a postcard.') ; }



2-1-2. How Long?


.length는 spaces, symbols, letters를 모두 센다. 

'I code'는 총 6개다. 공백도 포함하니까.



2-1-3. Chat Bot


이제는 .includes를 배우는 단계다. 어떤 문자열을 포함하는지를 지정(?)한다.

챗봇이 어떻게 기능하는지 맛이라도 약간 볼 수 있는 예제다.

제시되는 문장에 Hello가 들어가 있거나, bye가 들어가 있으면 어떻게 반응하라고 주문하는 예시다.


print (chat) ;

if (chat.includes('hello')) { print ('Hi, can I help you pick a destination?') ; }

if (chat.includes('bye')) { print ('see you later, have a great trip!') ; }



2-1-4. Is There a Day?


간단한 문제. 이 코드의 return값이 뭐냐. 이 경우에는 True가 나오는게 정답(이라는데 왜일까. 난 잘 모르겠다는....)

print ( 'Happy days'.includes('day') ) ; 



2-1-5. One Day Away


이번에 배우는건 .replace( )

Today is my birthday! 를 Tomorrow is my birthday! 로 바꾸라는게 예제.

아래와 같이 바꾸는게 정답인데, day를 morrow로 바꾸면, 뒤에 birthday도 birthmorrow로 바뀌어야 하지 않나?

설명에 따르면, .replace는 첫번째만 바꾸고 끝이다. 모두를 바꾸는게 아니란다.

var message = 'Today is my birthday!' ;

message = message.replace('day', 'morrow' ) ;

print (message) ; 


support에서 확인해보니 추가로 알려주는 내용이 있었다.

while loop를 쓰거나, 아니면 for와 if...else를 쓰면 두개를 다 바뀌게끔 할 수 있다.

var message = 'Today is my birhday!' ; 

while ( message.includes('day') ) { message = message.replace ('day', 'morrow') ;

print (message) ;


또는, 


var message = 'Today is my birhday!' ; 

for ( let i = 0 ; i < 1 ; i ) { if (message.includes('day') {message = message.replace ('day', 'morrow') ; }

  else { i = 1 ; } }

print (message) ;



그런데 현재까지, while, let이라는 명령을 배웠던가?



2-1-6. How Do You Do?


문제풀이다. 이 코드의 결과물은 뭐냐? 답이 너무 뻔하네.

var greeting = 'Hello, Grasshopper!' ;

greeting = greeting.replace('hopper', 'jumper') ;

print (greeting)



2-1-7. Altered Strings


지금까지 배운걸 다 써먹어보는 Code를 보여주고 복습해보는 시간

.length, .includes, .replace

var word = 'cruise' ;

var sentence = word + ' has XX letters' ;

if ( sentence.includes('XX') ) { print (sentence.replace('XX', word.length) ) ; }


Comments