'오름차순 정렬'에 해당되는 글 1건

  1. 2021.02.14 [ 아두이노 ] 입력받은 문자열 오름차순 정렬
아두이노2021. 2. 14. 00:42
728x90

[ 문제 ]

Serial Monitor에서 5개의 단어를 입력받은 후 문자열로 정렬하라.

 

[ 코드 ]

void setup() {

  // put your setup code here, to run once:

Serial.begin(9600);

}



void loop() {

  // put your main code here, to run repeatedly:

  int state = 1, i=0;

  char buffer[128];

  String str[5];



  while(true){

    while(i<5){

      if(state==1){

      Serial.print("Enter the ");

      Serial.print(i+1);

      Serial.print("th Word -->");

      state = 2;

      }

      while(Serial.available()){

      int len = Serial.readBytesUntil('\n',buffer,127);

      if(len>0){

        buffer[len] = '\0';

        str[i] = String(buffer);

        Serial.println(str[i]);

        i++;

        state = 1;

        break;

        }

       }

      }

    if(i==5)    break;

  }

  

    if(i==5){

    for(int a=0; a<4; a++){

      for(int b=a+1; b<5; b++){

        int compare = str[a].compareTo(str[b]);

        if(compare>0){ //오름차순

          String temp = str[a];

          str[a] = str[b];

          str[b] = temp;

        }

      }

    }



    Serial.println("After Sorting");

    for(int k=0;k<5;k++){

      Serial.println(str[k]);

    }

  }

}

 

[ 결과 ]

 

 

※ 제 글이 도움이 되었다면 공감 부탁드려요 :)

반응형
Posted by mminky