How to move all special characters to the beginning of a string in C++

2 Answers

0 votes
#include <iostream>

std::string move_special_characters_to_beginning(std::string s) { 
    int len = s.length(); 
    
    std::string chars = "", pecial_characters = ""; 
    for (int i = 0; i < len; i++) { 
        char ch = s.at(i); 
        if (isalnum(ch) || ch == ' ') 
            chars += ch; 
        else
            pecial_characters += ch; 
    } 
    
    return pecial_characters + chars; 
} 
    
int main() 
{ 
    std::string s("c++14$c&^java*(rust) php <>/python 3.14.2"); 
  
    std::cout << move_special_characters_to_beginning(s);
} 
  
  
/*
run:
  
++$&^*()<>/..c14cjavarust php python 3142
  
*/

 



answered Aug 13, 2019 by avibootz
edited Dec 12, 2025 by avibootz
0 votes
#include <iostream>
#include <string>
#include <cctype>   // for isalnum, isspace

std::string moveSpecialCharactersToBeginning(const std::string& s) {
    std::string specials;
    std::string chars;

    for (char ch : s) {
        if (std::isalnum(static_cast<unsigned char>(ch)) || std::isspace(static_cast<unsigned char>(ch))) {
            chars.push_back(ch);
        } else {
            specials.push_back(ch);
        }
    }

    return specials + chars;
}

int main() {
    std::string s = "c++23$c&^java*(rust) php <>/python 3.14.2";
    
    std::cout << moveSpecialCharactersToBeginning(s) << "\n";
}
 
  
  
/*
run:
  
++$&^*()<>/..c23cjavarust php python 3142
  
*/

 



answered Dec 12, 2025 by avibootz

Related questions

...