[c++] 반복문을 사용한 문자열 처리

반복문을 사용하여 C++에서 문자열을 처리하는 방법에 대해 알아보겠습니다.

  1. 문자열 길이 계산하기

    C++의 string 클래스를 사용하여 문자열의 길이를 계산할 수 있습니다. 반복문을 사용하여 문자열의 각 문자를 순회하면서 길이를 계산할 수 있습니다.

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main() {
        string text = "Hello, world!";
        int length = 0;
    
        for (int i = 0; i < text.length(); i++) {
            length++;
        }
    
        cout << "Length of the string: " << length << endl;
    
        return 0;
    }
    
  2. 문자열 역순으로 출력하기

    반복문을 사용하여 문자열을 역순으로 출력할 수 있습니다. 뒤에서부터 각 문자를 출력하거나 새로운 문자열에 역순으로 저장하여 출력할 수 있습니다.

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main() {
        string text = "Hello, world!";
        string reversed;
    
        for (int i = text.length() - 1; i >= 0; i--) {
            reversed += text[i];
        }
    
        cout << "Reversed string: " << reversed << endl;
    
        return 0;
    }
    
  3. 문자열에서 특정 문자 개수 세기

    반복문을 사용하여 문자열에서 특정 문자의 개수를 세는 예제입니다.

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main() {
        string text = "Hello, world!";
        char target = 'o';
        int count = 0;
    
        for (int i = 0; i < text.length(); i++) {
            if (text[i] == target) {
                count++;
            }
        }
    
        cout << "Number of '" << target << "' in the string: " << count << endl;
    
        return 0;
    }
    

이제 C++를 사용하여 반복문을 통해 문자열을 처리하는 방법에 대해 알게 되었습니다. 필요한 경우 위 예제 코드를 참고하시기 바랍니다.