Move All Hashes to the Front
Problem
Write a function that accepts a string containing some '#' characters and moves all the hashes to the front of the string, returning the whole string.
Example:
Input: Move#Hash#to#Front
Output: ###MoveHashtoFront
Code
import java.util.Scanner;
public class MoveHash {
public static String moveHash(String str) {
StringBuilder hashes = new StringBuilder();
StringBuilder letters = new StringBuilder();
for (char c : str.toCharArray()) {
if (c == '#') hashes.append(c);
else letters.append(c);
}
return hashes.toString() + letters.toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(moveHash(str));
}
}#include <stdio.h>
#include <string.h>
void moveHash(char str[]) {
int n = strlen(str);
char result[1000];
int idx = 0, hashCount = 0;
for (int i = 0; i < n; i++) {
if (str[i] == '#') hashCount++;
}
for (int i = 0; i < hashCount; i++) result[idx++] = '#';
for (int i = 0; i < n; i++) {
if (str[i] != '#') result[idx++] = str[i];
}
result[idx] = '\0';
printf("%s\n", result);
}
int main() {
char str[1000];
scanf("%s", str);
moveHash(str);
return 0;
}