You are given strings $S$ and $T$, consisting of lowercase English letters. It is guaranteed that $T$ is a permutation of the string abc.

Find string $S'$, the lexicographically smallest permutation of $S$ such that $T$ is not a subsequence of $S'$.

String $a$ is a permutation of string $b$ if the number of occurrences of each distinct character is the same in both strings.

A string $a$ is a subsequence of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements.

A string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds:

$a$ is a prefix of $b$, but $a \ne b$;

in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.


-----Input-----

Each test contains multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. Description of the test cases follows.

The first line of each test case contains a string $S$ ($1 \le |S| \le 100$), consisting of lowercase English letters.

The second line of each test case contains a string $T$ that is a permutation of the string abc. (Hence, $|T| = 3$).

Note that there is no limit on the sum of $|S|$ across all test cases.


-----Output-----

For each test case, output a single string $S'$, the lexicographically smallest permutation of $S$ such that $T$ is not a subsequence of $S'$.


-----Examples-----

Input
7
abacaba
abc
cccba
acb
dbsic
bac
abracadabra
abc
dddddddddddd
cba
bbc
abc
ac
abc
Output
aaaacbb
abccc
bcdis
aaaaacbbdrr
dddddddddddd
bbc
ac


-----Note-----

In the first test case, both aaaabbc and aaaabcb are lexicographically smaller than aaaacbb, but they contain abc as a subsequence.

In the second test case, abccc is the smallest permutation of cccba and does not contain acb as a subsequence.

In the third test case, bcdis is the smallest permutation of dbsic and does not contain bac as a subsequence.

Source: codeforces | Difficulty: EASY
Tags: Greedy algorithms

String algorithms

Sorting

Constructive algorithms


Solutions:
for _ in range(int(input())):
	s = input()
	t = input()
	ans = ''
	l = [0] * 26
	a = s.count('a')
	b = s.count('b')
	c = s.count('c')
	for i in s:
		l[ord(i) - 97] += 1
	if t[0] == 'a' and t[1] == 'b' and l[0]:
		for i in range(a):
			ans += 'a'
		for i in range(c):
			ans += 'c'
		for i in range(b):
			ans += 'b'
	else:
		for i in range(a):
			ans += 'a'
		for i in range(b):
			ans += 'b'
		for i in range(c):
			ans += 'c'
	for i in range(3, 26):
		for j in range(l[i]):
			ans += chr(i + 97)
	print(ans)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	a = sorted(input().strip())
	t = input().strip()
	one = a.count(t[0])
	two = a.count(t[1])
	thr = a.count(t[2])
	if one > 0 and two > 0 and (thr > 0):
		if t[0] == 'a':
			print(t[0] * one + t[2] * thr + t[1] * two, end='')
		else:
			print('a' * a.count('a') + 'b' * a.count('b') + 'c' * a.count('c'), end='')
	elif one + two + thr == 0:
		print('', end='')
	elif one + two == 0:
		print(t[2] * thr, end='')
	elif one + thr == 0:
		print(t[1] * two, end='')
	elif two + thr == 0:
		print(t[0] * one, end='')
	elif one == 0:
		if t[1] > t[2]:
			print(t[2] * thr + t[1] * two, end='')
		else:
			print(t[1] * two + t[2] * thr, end='')
	elif two == 0:
		if t[0] > t[2]:
			print(t[2] * thr + t[0] * one, end='')
		else:
			print(t[0] * one + t[2] * thr, end='')
	elif thr == 0:
		if t[1] > t[0]:
			print(t[0] * one + t[1] * two, end='')
		else:
			print(t[1] * two + t[0] * one, end='')
	print(''.join(a[one + two + thr:]))


for _ in range(int(input())):
	s = input()
	t = input()
	if t[0] not in s or t[1] not in s or t[2] not in s:
		print(''.join(sorted(s)))
	elif t != 'abc':
		print(''.join(sorted(s)))
	else:
		a1 = s.count('a')
		b1 = s.count('b')
		c1 = s.count('c')
		s1 = sorted(s)
		viv = ''.join(s1[a1 + c1 + b1:])
		print(a1 * 'a' + c1 * 'c' + b1 * 'b' + viv)


for _ in range(int(input())):
	s = input()
	t = input()
	x = [0] * 3
	xd = []
	for i in range(len(s)):
		if s[i] == 'a':
			x[0] += 1
		elif s[i] == 'b':
			x[1] += 1
		elif s[i] == 'c':
			x[2] += 1
		else:
			xd += [s[i]]
	xd = sorted(xd)
	if x[0] > 0 and x[1] > 0 and (x[2] > 0) and (t == 'abc'):
		for _ in range(x[0]):
			print('a', end='')
		for _ in range(x[2]):
			print('c', end='')
		for _ in range(x[1]):
			print('b', end='')
		for i in range(len(xd)):
			print(xd[i], end='')
		print()
	else:
		for _ in range(x[0]):
			print('a', end='')
		for _ in range(x[1]):
			print('b', end='')
		for _ in range(x[2]):
			print('c', end='')
		for i in range(len(xd)):
			print(xd[i], end='')
		print()


for _ in range(int(input())):
	s = input()
	t = input()
	d = sorted(s)
	flag = 1
	for x in t:
		if x not in d:
			print(''.join(d))
			flag = 0
			break
	if flag:
		ans = ''
		cnt = 0
		i = -1
		if t == 'abc':
			for x in range(len(s)):
				if d[x] == 'c':
					cnt += 1
				if d[x] == 'a':
					i = x
			y = ''
			for l in range(cnt):
				y += 'c'
			for x in range(len(s)):
				if x == i + 1:
					ans += y
				if d[x] == 'c':
					continue
				else:
					ans += d[x]
			print(ans)
		else:
			print(''.join(d))


def solve():
	s = input()
	t = input()
	ca = s.count('a')
	cb = s.count('b')
	cc = s.count('c')
	sort = sorted((c for c in s))
	if ca * cb * cc == 0 or t != 'abc':
		print(''.join(sort))
		return
	print(ca * 'a', cc * 'c', cb * 'b', sep='', end='')
	for c in sort[ca + cb + cc:]:
		print(c, end='')
	print()
for _ in range(int(input())):
	solve()


n = int(input())
for i in range(n):
	a = list(input())
	t = input()
	n = len(a)
	a.sort()
	if t == 'abc':
		i = 0
		j = n - 1
		flag = 0
		for i in range(n):
			if a[i] == 'a':
				flag += 1
				break
		while i < j and flag:
			while i < j and a[i] != 'b':
				i += 1
			while i < j and a[j] != 'c':
				j -= 1
			if i != j:
				a[i] = 'c'
				a[j] = 'b'
	print(''.join(a))


from sys import stdin
for _ in range(int(stdin.readline())):
	s = list(input())
	t = input()
	s.sort()
	if t == 'abc':
		a = s.count('a')
		b = s.count('b')
		c = s.count('c')
		ans = ''
		if a > 0 and b > 0 and (c > 0):
			d = {'a': 0, 'b': 2, 'c': 1, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 12, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26}
			s.sort(key=lambda x: d[x])
	print(''.join(s))


import sys, math, cmath, time, collections
from string import ascii_lowercase

def solve():
	s = insr()
	t = insr()
	if t != 'abc':
		print(sort_string(s))
	else:
		r = ''
		st = string_counter(s)
		for i in range(26):
			if i == 1:
				if st[0] == 0 or st[1] == 0 or st[2] == 0:
					r = r + ascii_lowercase[1] * st[1]
				else:
					r = r + ascii_lowercase[2] * st[2]
			elif i == 2:
				if st[0] == 0 or st[1] == 0 or st[2] == 0:
					r = r + ascii_lowercase[2] * st[2]
				else:
					r = r + ascii_lowercase[1] * st[1]
			elif st[i] != 0:
				r = r + ascii_lowercase[i] * st[i]
		print(r)

def main():
	global tt
	t = inp()
	for tt in range(1, t + 1):
		solve()

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def inls():
	return list(map(str, input().split()))

def insr():
	return input().strip()

def invr():
	return map(int, input().split())

def convert(set):
	return list(set)

def unique(list):
	list_set = set(list)
	unique_list = convert(list_set)
	return unique_list

def sort_string(string):
	r = sorted(string)
	return ''.join(r)

def reverse_string(string):
	return string[::-1]

def seive(n):
	a = []
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p ** 2, n + 1, p):
				prime[i] = False
		p = p + 1
	for p in range(2, n + 1):
		if prime[p]:
			a.append(p)
	return a

def counter(a):
	q = [0] * max(a)
	for i in range(len(a)):
		q[a[i] - 1] = q[a[i] - 1] + 1
	return q

def counter_elements(a):
	q = dict()
	for i in range(len(a)):
		if a[i] not in q:
			q[a[i]] = 0
		q[a[i]] = q[a[i]] + 1
	return q

def string_counter(a):
	q = [0] * 26
	for i in range(len(a)):
		q[ord(a[i]) - 97] = q[ord(a[i]) - 97] + 1
	return q

def factorial(n, m=1000000007):
	q = 1
	for i in range(n):
		q = q * (i + 1) % m
	return q

def factors(n):
	q = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			q.append(i)
			q.append(n // i)
	return list(sorted(list(set(q))))

def prime_factors(n):
	q = []
	while n % 2 == 0:
		q.append(2)
		n = n // 2
	for i in range(3, int(n ** 0.5) + 1, 2):
		while n % i == 0:
			q.append(i)
			n = n // i
	if n > 2:
		q.append(n)
	return list(sorted(q))

def transpose(a):
	(n, m) = (len(a), len(a[0]))
	b = [[0] * n for i in range(m)]
	for i in range(m):
		for j in range(n):
			b[i][j] = a[j][i]
	return b

def power_two(x):
	return x and (not x & x - 1)

def ceil(a, b):
	return -(-a // b)
main()


from sys import stdin, stdout
ts = int(stdin.readline())
for tt in range(ts):
	s = stdin.readline().strip()
	t = stdin.readline().strip()
	a = [c for c in s]
	a.sort()
	if t == 'abc' and a[0] == 'a':
		try:
			bi = a.index('b')
		except ValueError as e:
			bi = -1
		try:
			ci = a.index('c')
		except ValueError as e:
			ci = -1
		if bi != -1 and ci != -1:
			while ci + 1 < len(a) and a[ci + 1] == 'c':
				ci += 1
			while bi < ci and a[bi] == 'b' and (a[ci] == 'c'):
				(a[bi], a[ci]) = ('c', 'b')
				bi += 1
				ci -= 1
	stdout.write(''.join(a) + '\n')


def fix(S):
	(ca, cb, cc) = (0, 0, 0)
	for c in S:
		if c == 'a':
			ca += 1
		if c == 'b':
			cb += 1
		if c == 'c':
			cc += 1
	if ca == 0 or cb == 0 or cc == 0:
		return S
	S[ca:ca + cc] = ['c'] * cc
	S[ca + cc:ca + cc + cb] = ['b'] * cb
	return S

def solve():
	S = input()
	T = input()
	S = list(S)
	S.sort()
	if T == 'abc':
		S = fix(S)
	return ''.join(S)
T = int(input())
for i in range(T):
	print(solve())


def main():
	from collections import Counter
	for _ in range(int(input())):
		s = list(input())
		t = input()
		f = t == 'abc' and 'a' in s
		C = Counter(s)
		ans = ''
		i = 0
		while i < 26:
			if i == 1:
				if f:
					ans += 'c' * C[chr(2 + ord('a'))]
					ans += 'b' * C[chr(1 + ord('a'))]
				else:
					ans += 'b' * C[chr(1 + ord('a'))]
					ans += 'c' * C[chr(2 + ord('a'))]
				i += 2
				continue
			else:
				ans += chr(i + ord('a')) * C[chr(i + ord('a'))]
			i += 1
		print(ans)
main()


import collections

def lis(s, t):
	l = list(s)
	d = collections.Counter(l)
	ts = list(d.keys())
	ts.sort()
	if (len(s) < len(t)) | (t[0] not in s) | (t[1] not in s) | (t[2] not in s):
		ans = ''
		for x in ts:
			ans = ans + x * d.get(x)
		return ans
	elif t[:2] != 'ab':
		ans = 'a' * d.get('a') + 'b' * d.get('b') + 'c' * d.get('c')
		for x in ts[3:]:
			ans = ans + x * d.get(x)
		return ans
	else:
		ans = 'a' * d.get('a') + 'c' * d.get('c') + 'b' * d.get('b')
		for x in ts[3:]:
			ans = ans + x * d.get(x)
		return ans
n = int(input())
ip = []
ipt = []
op = []
for x in range(n):
	s = str(input())
	t = str(input())
	ip.append(s)
	ipt.append(t)
for i in range(len(ip)):
	ans = lis(ip[i], ipt[i])
	op.append(ans)
for x in op:
	print(x)


import sys, os, io
input = sys.stdin.readline
for _ in range(int(input())):
	s = list(input().strip())
	t = list(input().strip())
	s.sort()
	n = len(s)
	if t != ['a', 'b', 'c']:
		print(''.join(s))
		continue
	a = []
	b = []
	c = []
	rem = []
	for i in s:
		if i == 'a':
			a.append(i)
		elif i == 'b':
			b.append(i)
		elif i == 'c':
			c.append(i)
		else:
			rem.append(i)
	if len(a) == 0 or len(b) == 0 or len(c) == 0:
		f = a + b + c + rem
	else:
		f = a + c + b + rem
	print(''.join(f))


import sys
IN = sys.stdin
OUT = sys.stdout
tc = int(IN.readline())
for ti in range(tc):
	s = IN.readline().strip()
	t = IN.readline().strip()
	d = {}
	for c in s:
		d[c] = d.get(c, 0) + 1
	cc = sorted(d.keys())
	if 'a' in d and 'b' in d and ('c' in d) and ('abc' == t):
		cc[1] = 'c'
		cc[2] = 'b'
	ans = ''.join((d[c] * c for c in cc))
	print(ans)


def prepareString(str):
	bIndex = 0
	bEnd = 0
	cIndex = 0
	cEnd = len(str)
	for i in range(len(str)):
		if str[i] == 'b' and bIndex == 0:
			bIndex = i
		elif str[i] == 'c' and cIndex == 0:
			bEnd = i - 1
			cIndex = i
		elif str[i] > 'c':
			cEnd = i - 1
			break
	if cEnd == len(str) - 1:
		return str[0:bIndex] + str[cIndex:cEnd + 1] + str[bIndex:bEnd + 1]
	return str[0:bIndex] + str[cIndex:cEnd + 1] + str[bIndex:bEnd + 1] + str[cEnd + 1:]

def forbiddenSub(S, T):
	if T[0] > T[1] or T[1] > T[2]:
		return S
	else:
		letters = {'a': 0, 'b': 0, 'c': 0}
		ind = 0
		while ind < len(S) and S[ind] <= 'c':
			letters[S[ind]] = letters.get(S[ind]) + 1
			ind += 1
		if not (letters.get('c') and letters.get('b') and letters.get('a')):
			return S
		else:
			return prepareString(S)
cases = int(input())
for i in range(cases):
	S = input()
	T = input()
	S_ = sorted(S)
	print(''.join(forbiddenSub(S_, T)))


import sys
input = sys.stdin.readline

def iinput():
	return int(input())

def sinput():
	return input().rstrip()

def i0input():
	return int(input()) - 1

def linput():
	return list(input().split())

def liinput():
	return list(map(int, input().split()))

def miinput():
	return map(int, input().split())

def li0input():
	return list(map(lambda x: int(x) - 1, input().split()))

def mi0input():
	return map(lambda x: int(x) - 1, input().split())
INF = 10 ** 20
MOD = 1000000007
t = iinput()
for _ in [0] * t:
	s = sinput()
	t = sinput()
	if t != 'abc':
		print(''.join(sorted(s)))
	else:
		tmp = ''
		a = 0
		b = 0
		c = 0
		for ss in s:
			if ss == 'a':
				a += 1
			elif ss == 'b':
				b += 1
			elif ss == 'c':
				c += 1
			else:
				tmp += ss
		if a * b * c == 0:
			print(''.join(sorted(s)))
		else:
			print('a' * a + 'c' * c + 'b' * b + ''.join(sorted(tmp)))


n = int(input())
trans = str.maketrans('bc', 'cb')

def getOut(s1, s2):
	L = []
	countDic = {'a': 0, 'b': 0, 'c': 0}
	for i in range(len(s1)):
		if s1[i] in countDic:
			countDic[s1[i]] += 1
	if s2 == 'abc' and countDic['a'] > 0 and (countDic['b'] > 0) and (countDic['c'] > 0):
		s1 = s1.translate(trans)
		for i in range(len(s1)):
			L.append(s1[i])
		L.sort()
		return ''.join(L).translate(trans)
	else:
		for i in range(len(s1)):
			L.append(s1[i])
		L.sort()
		return ''.join(L)
for i in range(n):
	print(getOut(input(), input()))


from sys import stdin
from string import ascii_lowercase

def read_input():
	S = stdin.readline().rstrip()
	T = stdin.readline().rstrip()
	return (S, T)

def solve(S, T):
	answer = 0
	if T == 'abc':
		others = []
		for alphabet in ascii_lowercase:
			if alphabet != 'a' and alphabet != 'b' and (alphabet != 'c'):
				others.append(alphabet * S.count(alphabet))
		others = ''.join(others)
		if S.count('a') > 0:
			answer = S.count('a') * 'a' + S.count('c') * 'c' + S.count('b') * 'b' + others
		else:
			answer = S.count('b') * 'b' + S.count('c') * 'c' + others
	else:
		answer = [S.count(alphabet) * alphabet for alphabet in ascii_lowercase]
		answer = ''.join(answer)
	return answer

def main():
	t = int(stdin.readline())
	for _ in range(t):
		input = read_input()
		answer = solve(*input)
		print(answer)
main()


t = int(input())
for i in range(t):
	s1 = input()
	s2 = input()
	s3 = sorted(s1)
	n1 = s1.count('a')
	n2 = s1.count('b')
	n3 = s1.count('c')
	if s2 == 'abc':
		if n1 != 0:
			print(''.join(['a' * s1.count('a') + 'c' * s1.count('c') + 'b' * s1.count('b')] + s3[n1 + n2 + n3:]))
		else:
			print(''.join(s3))
	else:
		print(''.join(s3))


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
MOD = 10 ** 9 + 7
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def main():
	for _ in range(int(input())):
		a = input()
		b = input()
		x = [0] * 27
		for i in a:
			x[ord(i) - 97] += 1
		s = 'a' * x[0]
		if b == 'abc' and x[0] and x[1] and x[2]:
			s += 'c' * x[2]
			s += 'b' * x[1]
		else:
			s += 'b' * x[1]
			s += 'c' * x[2]
		for i in range(3, 27):
			s += chr(i + 97) * x[i]
		print(s)
main()


import sys
import io, os
import string
from io import BytesIO, IOBase
from os import path
from collections import Counter, OrderedDict
import itertools
from itertools import chain, combinations
import math
import random
import bisect
from functools import reduce
from sys import stdin, stdout
from math import gcd, floor, sqrt, log
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	input = sys.stdin.readline
sys.setrecursionlimit(100000000)
simp = lambda : int(input())
strng = lambda : input().strip()
jn = lambda x, l: x.join(map(str, l))
strl = lambda : list(input().strip())
mul = lambda : map(int, input().strip().split())
mulf = lambda : map(float, input().strip().split())
seq = lambda : list(map(int, input().strip().split()))
ceil = lambda x: int(x) if x == int(x) else int(x) + 1
ceildiv = lambda x, d: x // d if x % d == 0 else x // d + 1
flush = lambda : stdout.flush()
stdstr = lambda : stdin.readline()
stdint = lambda : int(stdin.readline())
stdpr = lambda x: stdout.write(str(x))
a = simp()

def if_its_binaryform_palindrome(n):
	res = 0
	k = n
	while k > 0:
		res = res << 1 | k & 1
		k = k >> 1
	return n == res

def solve(s, t):
	first = t[0]
	second = t[1]
	third = t[2]
	if 'a' not in s or 'b' not in s or 'c' not in s:
		sortedd = sorted(s)
		s = ''.join(sortedd)
		return s
	if s[0] == 'a' and t[0] != 'a':
		sortedd = sorted(s)
		s = ''.join(sortedd)
		return s
	elif t[0] != 'a':
		sortedd = sorted(s)
		s = ''.join(sortedd)
		return s
	sortedd = sorted(s)
	s = ''.join(sortedd)
	d = Counter(s)
	r = ''
	if t[1] == 'b':
		rr = ''
		for (i, j) in d.items():
			if i == 'a':
				r += i * j
			elif i == 'b' and r[-1] == 'a':
				rr += i * j
			elif i == 'c':
				r += i * j
				r += rr
			else:
				r += i * j
		return r
	elif t[1] == 'c':
		rr = ''
		for (i, j) in d.items():
			if i == 'a':
				r += i * j
			elif i == 'c' and r[-1] == 'a':
				rr += i * j
			elif i == 'b':
				r += i * j
				r += rr
			else:
				r += i * j
		return r
for i in range(a):
	t = strng()
	d = strng()
	print(solve(t, d))

def seive(n):
	prime = [1 for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == 1:
			for i in range(p ** 2, n + 1, p):
				prime[i] = 0
		p += 1
	prime[0] = 0
	prime[1] = 0
	for i in range(1, n + 1):
		prime[i] += prime[i - 1]
	return prime

def list_of_prime_sieve(n):
	primes = [True] * (n + 1)
	primes[0] == primes[1] == False
	for i in range(2, int(n ** (1 / 2)) + 1):
		if primes[i] == True:
			for j in range(i * i, n + 1, i):
				primes[j] = False
	list_primes = []
	for i in range(2, len(primes)):
		if primes[i] == True:
			list_primes.append(i)
	return list_primes

def count_primes(a):
	return len(list_of_prime_sieve(a))

def gcdoftwo(a, b):
	if a == 0:
		return b
	else:
		return gcdoftwo(b % a, a)

def lcm(a, b):
	return a * b // gcdoftwo(a, b)

def gcdofList(A):
	res = A[0]
	for c in A[1:]:
		res = gcdoftwo(res, c)
		if res == 1:
			return res
	return res

def binpow(a, b):
	res = 1
	while b > 0:
		if b & 1:
			res = res * a
		a = a * a
		b >>= 1
	return res

def fibo_in_logn(n):
	if n == 0:
		return [0, 1]
	p = fibo_in_logn(n >> 1)
	c = p.first * (2 * p.second - p.first)
	d = p.first * p.first + p.second * p.second
	if n & 1:
		return {d, c + d}
	else:
		return {c, d}

def x_n_mod_m(a, b, m):
	a = a % m
	res = 1
	while b > 0:
		if b & 1:
			res = res * a % m
		a = a * a % m
		b >>= 1
	return res

def change_array(count, t):
	emp = []
	for i in range(len(t)):
		emp.append(count[t[i]])
	return emp

def simpleSieve(limit):
	mark = [True for i in range(limit + 1)]
	p = 2
	while p * p <= limit:
		if mark[p] == True:
			for i in range(p * p, limit + 1, p):
				mark[i] = False
		p += 1
	for p in range(2, limit):
		if mark[p]:
			prime.append(p)
	return prime

def segmentedSieve(n):
	limit = int(math.floor(math.sqrt(n)) + 1)
	t = []
	t += simpleSieve(limit)
	low = limit
	high = limit * 2
	while low < n:
		if high >= n:
			high = n
		mark = [True for i in range(limit + 1)]
		for i in range(len(prime)):
			loLim = int(math.floor(low / prime[i]) * prime[i])
			if loLim < low:
				loLim += prime[i]
			for j in range(loLim, high, prime[i]):
				mark[j - low] = False
		for i in range(low, high):
			if mark[i - low]:
				t.append(i)
		low = low + limit
		high = high + limit
	return t
mod = 1000000007

def occurrences(string, sub):
	count = start = 0
	while True:
		start = string.find(sub, start) + 1
		if start > 0:
			count += 1
		else:
			return count


import re
I = input
for _ in [0] * int(I()):
	s = ''.join(sorted(I()))
	if 'abc' == I():
		s = re.sub('(a+)(b+)(c+)', '\\1\\3\\2', s)
	print(s)


for jj in range(int(input())):
	(s, t) = (input(), input())
	s1 = sorted(list(s))
	s2 = ''.join(s1)
	if t != 'abc':
		print(s2)
	elif 'a' in s and 'b' in s and ('c' in s):
		(a, b, c) = (s.count('a'), s.count('b'), s.count('c'))
		print('a' * a + 'c' * c + 'b' * b + ''.join(s1[a + b + c:]))
	else:
		print(s2)


def main():
	for _ in range(int(input())):
		s = ''.join(sorted(input()))
		t = input()
		A = 0
		B = 0
		C = 0
		for c in s:
			if c == 'a':
				A += 1
			if c == 'b':
				B += 1
			if c == 'c':
				C += 1
		if t != 'abc' or A * B * C == 0:
			print(s)
		else:
			(B, C) = (0, 0)
			D = ''
			for c in s:
				if c == 'a':
					print('a', end='')
				elif c == 'b':
					B += 1
				elif c == 'c':
					C += 1
				else:
					D += c
			print(C * 'c' + B * 'b' + D)
main()


kl = int(input())
for kkl in range(kl):
	str = input()
	t = input()
	sp = list(str)
	sp.sort()
	sp.append(1)
	i = 0
	if 'a' in sp and 'b' in sp and ('c' in sp) and (t == 'abc'):
		while sp[i] == 'a':
			i += 1
		ka = i
		while (sp[i] == 'c' or sp[i] == 'b') and i < len(sp):
			i += 1
		if i == len(sp):
			i += 1
		sp1 = sp[ka:i]
		sp1.reverse()
		sp[ka:i] = sp1
	for i in range(len(sp) - 1):
		print(sp[i], end='')
	print()


t = int(input())
for _ in range(0, t):
	c = [0 for i in range(0, 123)]
	a = input()
	b = input()
	a1 = 0
	b1 = 0
	c1 = 0
	ans = ''
	ans1 = []
	for ele in a:
		if ele == 'a':
			a1 += 1
		elif ele == 'b':
			b1 += 1
		elif ele == 'c':
			c1 += 1
		else:
			ans1.append(ele)
	ans1.sort()
	if a1 > 0 and b1 > 0 and (c1 > 0):
		if b == 'abc':
			for i in range(0, a1):
				ans += 'a'
			for i in range(0, c1):
				ans += 'c'
			for i in range(0, b1):
				ans += 'b'
			for ele in ans1:
				ans += ele
		elif b == 'acb':
			for i in range(0, a1):
				ans += 'a'
			for i in range(0, b1):
				ans += 'b'
			for i in range(0, c1):
				ans += 'c'
			for ele in ans1:
				ans += ele
		else:
			for i in range(0, a1):
				ans += 'a'
			for i in range(0, b1):
				ans += 'b'
			for i in range(0, c1):
				ans += 'c'
			for ele in ans1:
				ans += ele
	else:
		for i in range(0, a1):
			ans += 'a'
		for i in range(0, b1):
			ans += 'b'
		for i in range(0, c1):
			ans += 'c'
		for ele in ans1:
			ans += ele
	print(ans)


for _ in range(int(input())):
	s = list(input())
	t = list(input())
	s.sort()
	b = list(set(s))
	b.sort()
	if ''.join(b).find(''.join(t)) == -1:
		print(''.join(s))
	else:
		d = dict()
		for i in s:
			if i not in d.keys():
				d[i] = 1
			else:
				d[i] += 1
		ans = []
		for i in b:
			if i not in t:
				ans.append(i)
		(t[-1], t[-2]) = (t[-2], t[-1])
		st = ''
		for i in t:
			st += d[i] * i
		for i in ans:
			st += d[i] * i
		print(st)


def find(s, t):
	L = list(s)
	L.sort()
	if 'a' not in s or 'b' not in s or 'c' not in s:
		return ''.join(L)
	if t != 'abc':
		return ''.join(L)
	if L[-1] in ['a', 'b', 'c']:
		L.append('555')
	a = 0
	b = 0
	c = 0
	while L[0] == 'a':
		a += 1
		L.remove('a')
	while L[0] == 'b':
		b += 1
		L.remove('b')
	while L[0] == 'c':
		c += 1
		L.remove('c')
	if L[-1] == '555':
		L.pop()
		return 'a' * a + 'c' * c + 'b' * b + ''.join(L)
	return 'a' * a + 'c' * c + 'b' * b + ''.join(L)
cases = int(input())
for i in range(cases):
	s = input()
	t = input()
	print(find(s, t))


from sys import stdin
import math
from collections import deque
from heapq import heapify, heappop, heappush
from bisect import bisect_left, bisect_right
input = stdin.readline

def log(n, m):
	(res, val) = (0, 1)
	while True:
		if n == val:
			return res
		elif n > val:
			return res - 1
		res += 1
		val *= m

def ceil(m, n):
	val = m // n
	if m % n != 0:
		return val + 1
	return val
for _ in range(int(input())):
	s = input().strip()
	t = input().strip()
	d = {}
	for c in s:
		d[c] = d.get(c, 0) + 1
	if 'a' not in d or 'b' not in d or 'c' not in d or (t != 'abc'):
		print(''.join(sorted(s)))
		continue
	res = ''
	for key in ['a', 'c', 'b']:
		res += key * d[key]
	for key in sorted(d.keys()):
		if key in 'abc':
			continue
		res += key * d[key]
	print(res)


for _ in range(int(input())):
	s = input()
	t = input()
	count = [0 for i in range(26)]
	for i in s:
		count[ord(i) - 97] += 1
	if count[0] == 0 or count[1] == 0 or count[2] == 0:
		for i in range(26):
			print(chr(97 + i) * count[i], end='')
		print()
	elif t == 'abc':
		print(chr(97) * count[0], end='')
		print(chr(99) * count[2], end='')
		print(chr(98) * count[1], end='')
		for i in range(3, 26):
			print(chr(97 + i) * count[i], end='')
		print()
	else:
		for i in range(26):
			print(chr(97 + i) * count[i], end='')
		print()


for _ in range(int(input())):
	s = input().strip()
	t = input().strip()
	fs = {}
	for char in s:
		fs[char] = fs.get(char, 0) + 1
	ft = {}
	for char in t:
		ft[char] = ft.get(char, 0) + 1
	flag = False
	for char in ft:
		if ft[char] > fs.get(char, 0):
			flag = True
			break
	if flag:
		ans = ''.join(sorted(s))
	elif t != ''.join(sorted(t)):
		ans = ''.join(sorted(s))
	else:
		(*_, c1, c2) = t
		ans = ''
		for char in sorted(fs.keys()):
			if char == c1:
				pass
			elif char == c2:
				ans += c2 * fs[c2] + c1 * fs[c1]
			else:
				ans += char * fs[char]
	print(ans)


for _ in range(int(input())):
	s = input()
	T = input()
	s2 = ''.join(sorted(s))
	if T == 'abc' and 'a' in s2 and ('b' in s2) and ('c' in s2):
		s2 = [i for i in s2]
		ind2 = len(s2) - 1 - s2[::-1].index('c')
		ind1 = s2.index('c')
		ind0 = len(s2) - 1 - s2[::-1].index('a')
		s2 = s2[:ind0 + 1] + s2[ind1:ind2 + 1] + s2[ind0 + 1:ind1] + s2[ind2 + 1:]
		s2 = ''.join(s2)
	print(s2)


from string import ascii_lowercase
for _ in range(int(input())):
	s = input()
	t = input()
	s = ''.join(sorted(s))
	if t == 'abc' and 'a' in s and ('b' in s) and ('c' in s):
		m = {c: s.count(c) for c in ascii_lowercase}
		for _ in range(m['a']):
			print('a', end='')
		for _ in range(m['c']):
			print('c', end='')
		for _ in range(m['b']):
			print('b', end='')
		for c in ascii_lowercase[3:]:
			for _ in range(m[c]):
				print(c, end='')
		print()
	else:
		print(s)


import array
import bisect
import heapq
import math
import collections
import sys
import copy
from functools import reduce
import decimal
from io import BytesIO, IOBase
import os
import itertools
import functools
from types import GeneratorType
decimal.getcontext().rounding = decimal.ROUND_HALF_UP
graphDict = collections.defaultdict
queue = collections.deque

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		to = f(*args, **kwargs)
		if stack:
			return to
		else:
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						return to
					to = stack[-1].send(to)
	return wrappedfunc

class Graphs:

	def __init__(self):
		self.graph = graphDict(set)

	def add_edge(self, u, v):
		self.graph[u].add(v)
		self.graph[v].add(u)

	def dfs_utility(self, nodes, visited_nodes, colors, parity, level):
		global count
		if nodes == 1:
			colors[nodes] = -1
		elif len(self.graph[nodes]) == 1 and parity % 2 == 0:
			if q == 1:
				colors[nodes] = 1
			else:
				colors[nodes] = -1
				count += 1
		elif parity % 2 == 0:
			colors[nodes] = -1
		else:
			colors[nodes] = 1
		visited_nodes.add(nodes)
		for neighbour in self.graph[nodes]:
			new_level = level + 1
			if neighbour not in visited_nodes:
				self.dfs_utility(neighbour, visited_nodes, colors, level - 1, new_level)

	def dfs(self, node):
		Visited = set()
		color = collections.defaultdict()
		self.dfs_utility(node, Visited, color, 0, 0)
		return color

	def bfs(self, node, f_node):
		count = float('inf')
		visited = set()
		level = 0
		if node not in visited:
			queue.append([node, level])
			visited.add(node)
		flag = 0
		while queue:
			parent = queue.popleft()
			if parent[0] == f_node:
				flag = 1
				count = min(count, parent[1])
			level = parent[1] + 1
			for item in self.graph[parent[0]]:
				if item not in visited:
					queue.append([item, level])
					visited.add(item)
		return count if flag else -1
		return False

class Tree:

	def __init__(self, data):
		self.data = data
		self.left = None
		self.right = None

def inorder(node, lis):
	if node:
		inorder(node.left, lis)
		lis.append(node.data)
		inorder(node.right, lis)
	return lis

def leaf_node_sum(root):
	if root is None:
		return 0
	if root.left is None and root.right is None:
		return root.data
	return leaf_node_sum(root.left) + leaf_node_sum(root.right)

def hight(root):
	if root is None:
		return -1
	if root.left is None and root.right is None:
		return 0
	return max(hight(root.left), hight(root.right)) + 1

class UnionFind:
	parents = []
	sizes = []
	count = 0

	def __init__(self, n):
		self.count = n
		self.parents = [i for i in range(n)]
		self.sizes = [1 for i in range(n)]

	def find(self, i):
		if self.parents[i] == i:
			return i
		else:
			self.parents[i] = self.find(self.parents[i])
			return self.parents[i]

	def unite(self, i, j):
		root_i = self.find(i)
		root_j = self.find(j)
		if root_i == root_j:
			return
		elif root_i < root_j:
			self.parents[root_j] = root_i
			self.sizes[root_i] += self.sizes[root_j]
		else:
			self.parents[root_i] = root_j
			self.sizes[root_j] += self.sizes[root_i]

	def same(self, i, j):
		return self.find(i) == self.find(j)

	def size(self, i):
		return self.sizes[self.find(i)]

	def group_count(self):
		return len(set((self.find(i) for i in range(self.count))))

	def answer(self, extra, p, q):
		dic = collections.Counter()
		for q in range(n):
			dic[self.find(q)] = self.size(q)
		hq = list(dic.values())
		heapq._heapify_max(hq)
		ans = -1
		for z in range(extra + 1):
			if hq:
				ans += heapq._heappop_max(hq)
			else:
				break
		return ans

def rounding(n):
	return int(decimal.Decimal(f'{n}').to_integral_value())

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

def p_sum(array):
	return list(itertools.accumulate(array))

def base_change(nn, bb):
	if nn == 0:
		return [0]
	digits = []
	while nn:
		digits.append(int(nn % bb))
		nn //= bb
	return digits[::-1]

def diophantine(a: int, b: int, c: int):
	(d, x, y) = extended_gcd(a, b)
	r = c // d
	return (r * x, r * y)

@bootstrap
def extended_gcd(a: int, b: int):
	if b == 0:
		(d, x, y) = (a, 1, 0)
	else:
		(d, p, q) = (yield extended_gcd(b, a % b))
		x = q
		y = p - q * (a // b)
	yield (d, x, y)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self, **kwargs):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def inp():
	return sys.stdin.readline().strip()

def map_inp(v_type):
	return map(v_type, inp().split())

def list_inp(v_type):
	return list(map_inp(v_type))
all_p = list(itertools.permutations(['a', 'b', 'c']))
all_p.sort()
for _ in range(int(inp())):
	s = list(inp())
	t = list(inp())
	for item in all_p:
		if list(item) != t:
			t = queue(item)
			break
	dic = collections.Counter(s)
	if dic['a'] == 0 or dic['b'] == 0 or dic['c'] == 0:
		s.sort()
		print(''.join(s))
	else:
		ans = ''
		order = list(dic.keys())
		order.sort()
		i = 0
		for item in order:
			if item in t:
				x = t[i]
				ans += x * dic[x]
				i += 1
			else:
				ans += item * dic[item]
		print(ans)


for _ in range(int(input())):
	s = input()
	t = input()
	s = ''.join(sorted(list(s)))
	if t != 'abc':
		print(s)
	else:
		f = {chr(i): 0 for i in range(97, 123)}
		for c in s:
			f[c] += 1
		x = 'a' * f['a']
		if len(x):
			x += 'c' * f['c']
			x += 'b' * f['b']
		else:
			x += 'b' * f['b']
			x += 'c' * f['c']
		f['a'] = f['b'] = f['c'] = 0
		for (key, cnt) in f.items():
			x += key * cnt
		print(x)


def find_string(s, t):
	s = s
	t = t
	s1 = sorted(s)
	s1 = ''.join(s1)
	if t != 'abc' or 'b' not in s1 or 'a' not in s1 or ('c' not in s1):
		print(s1)
	else:
		a1 = s.count('a')
		b1 = s.count('b')
		c1 = s.count('c')
		y = []
		for i in s1:
			if i != 'a' and i != 'b' and (i != 'c'):
				y.append(i)
		later = ''.join(y)
		firts = 'a' * a1 + 'c' * c1 + 'b' * b1
		print(firts + later)
t1 = int(input())
while t1:
	s = input()
	t = input()
	find_string(s, t)
	t1 -= 1


test = int(input())
for tt in range(test):
	l = list(input())
	t = input()
	l.sort()
	s = ''.join(l)
	if t != 'abc' or s.count('a') == 0 or s.count('b') == 0 or (s.count('c') == 0):
		print(s)
		continue
	ix = s.find('c')
	ic = len(s)
	for i in range(ix, len(s)):
		if s[i] != 'c':
			ic = i
			break
	ans = 'a' * s.count('a') + 'c' * s.count('c') + 'b' * s.count('b') + s[ic:]
	print(ans)


t = int(input())

def do(s, t):
	if t[0] not in s or t[1] not in s or t[2] not in s:
		ans = ''
		for i in sorted(list(s)):
			ans += i
		print(ans)
		return
	l = list(s)
	l.sort()
	ans = ''
	if t != 'abc':
		for i in l:
			ans += i
	else:
		for i in l:
			ans += i
		c = s.count('b')
		ans = ans.replace('b', '')
		ind = ans[::-1].index('c')
		ans = ans[:len(ans) - ind] + 'b' * c + ans[len(ans) - ind:]
	print(ans)
	return
for i in range(t):
	s = input()
	t = input()
	do(s, t)


import sys
import collections as cc
I = lambda : list(map(int, input().split()))
mod = 10 ** 9 + 7

def ch(temp):
	tans = 0
	for i in range(len(temp) - k - 1, -1, -k):
		tans += 2 * abs(temp[i])
	return tans
for tc in range(int(input())):
	s = input()
	t = input()
	ar = [s.count('a'), s.count('b'), s.count('c')]
	new = [i for i in s if i not in ['a', 'b', 'c']]
	new.sort()
	if t != 'abc' or (ar[0] == 0 or ar[1] == 0 or ar[2] == 0):
		print('a' * ar[0] + 'b' * ar[1] + 'c' * ar[2] + ''.join(new))
	else:
		print('a' * ar[0] + 'c' * ar[2] + 'b' * ar[1] + ''.join(new))


for _ in range(int(input())):
	s = input()
	t = input()
	if 'a' not in s or 'b' not in s or 'c' not in s:
		s = ''.join(sorted(s))
		print(s)
	elif t != 'abc':
		s = ''.join(sorted(s))
		print(s)
	else:
		s = sorted(s)
		count_a = s.count('a')
		count_b = s.count('b')
		count_c = s.count('c')
		ans = 'a' * count_a + 'c' * count_c + 'b' * count_b
		s = ''.join(s)
		ans += s[count_a + count_b + count_c:]
		print(ans)


for _ in [0] * int(input()):
	s = sorted(input())
	t = str(input())
	if t != 'abc':
		print(''.join(s))
	else:
		x = s.count('a')
		y = s.count('b')
		z = s.count('c')
		if x:
			print('a' * x + 'c' * z + 'b' * y + ''.join([i for i in s if i not in 'abc']))
		else:
			print('b' * y + 'c' * z + ''.join([i for i in s if i not in 'abc']))


k = int(input())
for j in range(k):
	s = input()
	t = input()
	s = list(s)
	s.sort()
	if 'a' not in s or 'b' not in s or 'c' not in s:
		print(*s, sep='')
	elif t != 'abc':
		print(*s, sep='')
	else:
		a = False
		count = 0
		otv = ''
		for i in s:
			if i == 'b':
				count += 1
			elif i == 'c':
				a = True
			if i != 'c' and a == True:
				otv += 'b' * count
				count = 0
				a = False
			if i != 'b':
				otv += i
		if a == True and count != 0:
			otv += 'b' * count
		print(otv)


import sys
import pprint
import logging
from logging import getLogger

def input():
	return sys.stdin.readline().rstrip('\r\n')
logging.basicConfig(format='%(message)s', level=logging.WARNING)
logger = getLogger(__name__)
logger.setLevel(logging.INFO)

def debug(msg, *args):
	logger.info(f'{msg}={pprint.pformat(args)}')
import collections
for _ in range(int(input())):
	s = ''.join(sorted(input()))
	t = input()
	idx = 0
	for i in range(len(s)):
		if idx == 3:
			break
		if s[i] == t[idx]:
			idx += 1
	if idx < 3:
		print(s)
	else:
		d = collections.defaultdict(int)
		for i in s:
			d[i] += 1
		res = d['a'] * 'a' + d['c'] * 'c' + d['b'] * 'b'
		for i in 'defghijklmnopqrstuvwxyz':
			res += d[i] * i
		print(res)


for _ in range(int(input())):
	s = sorted(input())
	s1 = input()
	if 'a' in s and 'b' in s and ('c' in s) and (s1 == 'abc'):
		s = ''.join((str(x) for x in s))
		a = s.count('a')
		b = s.count('b')
		c = s.count('c')
		r = a + b + c
		s = 'a' * a + 'c' * c + 'b' * b + s[r:]
	else:
		s = ''.join((str(x) for x in s))
	print(s)


for i in range(int(input())):
	s = input()
	t = input()
	b = ''.join(sorted(s))
	if t == 'abc' and (('a' in s and 'b' in s) and 'c' in s):
		list_s = list(b)
		k = list_s.count('a')
		m = list_s.count('c')
		for i in range(m):
			list_s.remove('c')
		for i in range(m):
			list_s.insert(k, 'c')
		print(''.join(list_s))
	else:
		print(b)


tst = int(input())
for i in range(tst):
	s = ''.join(sorted(input()))
	t = input()
	a = s.count('a')
	b = s.count('b')
	c = s.count('c')
	if t == 'abc' and 'a' in s and ('b' in s) and ('c' in s):
		print(a * 'a' + c * 'c' + b * 'b' + s[a + b + c:])
	else:
		print(s)


t = int(input())
for i in range(t):
	s = input()
	t = input()
	a = list(s)
	a.sort()
	if 'a' not in s or 'b' not in s or 'c' not in s:
		print(''.join(a))
	else:
		ans = ''
		if t[1] == 'b' and t[2] == 'c':
			temp = ''
			for i in a:
				if i == 'a':
					ans += 'a'
				elif i == 'c':
					ans += 'c'
				else:
					temp += i
			ans += temp
			print(ans)
		else:
			print(''.join(a))


for _ in range(int(input())):
	s = list(input())
	T = input()
	S2 = sorted(s)
	if T == 'abc' and T in ''.join(sorted(list(set(S2)))):
		result = [i for i in S2 if i == 'a' or i == 'c']
		result = result + [i for i in S2 if i != 'a' and i != 'c']
		print(''.join(result))
	else:
		print(''.join(S2))


test = int(input())
for g in range(0, test):
	s = input()
	t = input()
	ac = s.count('a')
	bc = s.count('b')
	cc = s.count('c')
	if ac == 0 or bc == 0 or cc == 0:
		res = ''.join(sorted(s))
		print(res)
	else:
		ex = ''
		res = ''
		o = ['a', 'b', 'c']
		for y in s:
			if y not in o:
				ex = ex + y
		if t == 'abc':
			for j in range(0, ac):
				res = res + 'a'
			for j in range(0, cc):
				res = res + 'c'
			for j in range(0, bc):
				res = res + 'b'
		else:
			for j in range(0, ac):
				res = res + 'a'
			for j in range(0, bc):
				res = res + 'b'
			for j in range(0, cc):
				res = res + 'c'
		ex = ''.join(sorted(ex))
		res = res + ex
		print(res)


t = int(input())
for x in range(t):
	s = input()
	t1 = input()
	if s.count('a') == 0 or s.count('b') == 0 or s.count('c') == 0:
		s = ''.join(sorted(s))
		s = str(s)
		print(s)
	elif t1[0] != 'a':
		s = ''.join(sorted(s))
		s = str(s)
		print(s)
	elif t1 == 'acb':
		s = ''.join(sorted(s))
		s = str(s)
		print(s)
	else:
		a = s.count('a')
		c = s.count('c')
		b = s.count('b')
		ans = ''
		ans = ans + 'a' * a + 'c' * c + 'b' * b
		lst = []
		for j in s:
			if j != 'a' and j != 'b' and (j != 'c'):
				lst.append(j)
		lst.sort()
		for j in lst:
			ans = ans + j
		print(ans)


for i in range(int(input())):
	s = input()
	t = input()
	if t != 'abc':
		print(''.join(sorted(s)))
	elif not all((c in s for c in 'abc')):
		print(''.join(sorted(s)))
	else:
		s2 = s.translate(str.maketrans('bc', 'cb'))
		s2 = ''.join(sorted(s2))
		s = s2.translate(str.maketrans('bc', 'cb'))
		print(s)


from collections import defaultdict

def solve(string, ref):
	string.sort()
	count = defaultdict(int)
	for i in string:
		count[i] += 1
	if count['a'] > 0 and count['b'] > 0 and (count['c'] > 0):
		if ref != ['a', 'b', 'c']:
			return string
		ans = ''
		for _ in range(count['a']):
			ans += 'a'
		for _ in range(count['c']):
			ans += 'c'
		for _ in range(count['b']):
			ans += 'b'
		for (key, value) in count.items():
			if key != 'a' and key != 'b' and (key != 'c'):
				for _ in range(value):
					ans += key
		return ans
	return string
t = int(input())
for _ in range(t):
	string = list(input())
	ref = list(input())
	print(''.join(solve(string, ref)))


t = int(input())
for i in range(t):
	s = input()
	pr = input()
	d = {}
	for el in s:
		if el in d.keys():
			d[el] += 1
		else:
			d[el] = 1
	ans = ''
	for el in sorted(d.keys()):
		while d[el] > 0:
			ans += el
			d[el] -= 1
	new_ans = ''
	if pr == 'abc' and 'a' in ans and ('b' in ans) and ('c' in ans):
		ccount = ans.count('c')
		bcount = ans.count('b')
		ans = ans.replace('b', 'c', min(bcount, ccount))
		ans = ans[::-1].replace('c', 'b', min(bcount, ccount))[::-1]
	print(ans)


import sys
input = sys.stdin.readline

def solve():
	S = input().strip()
	T = input().strip()
	S = list(S)
	S.sort()
	S = ''.join(S)
	if T == 'abc' and 'ab' in S and ('bc' in S):
		cnt = [0] * 26
		for c in S:
			cnt[ord(c) - ord('a')] += 1
		return 'a' * cnt[0] + 'c' * cnt[2] + 'b' * cnt[1] + S[cnt[0] + cnt[1] + cnt[2]:]
	else:
		return S
for _ in range(int(input())):
	print(solve())


import sys
n = int(sys.stdin.readline())
for i in range(n):
	S = sys.stdin.readline().replace('\n', '')
	T = sys.stdin.readline().replace('\n', '')
	sorted_S = ''.join(sorted(S))
	if 'a' not in S or 'b' not in S or 'c' not in S or (T != 'abc'):
		print(sorted_S)
		continue
	result = ''
	a_count = S.count('a')
	c_count = S.count('c')
	b_count = S.count('b')
	result = 'a' * a_count + 'c' * c_count + 'b' * b_count + sorted_S[a_count + c_count + b_count:len(S)]
	print(result)


def solve(a, t):
	if t == 'abc':
		s = sorted(a)
		if a.count('a') > 0:
			new_string = 'a' * a.count('a') + 'c' * a.count('c') + 'b' * a.count('b')
			for i in range(len(new_string)):
				s[i] = new_string[i]
		return ''.join([x for x in s])
	else:
		return ''.join([x for x in sorted(a)])
t = int(input())
for test_case in range(t):
	string = input()
	pattern = input()
	print(solve(string, pattern))


import sys
import math
from bisect import bisect_right as br
from collections import deque
from itertools import combinations as cb

def int_arr():
	return list(map(int, sys.stdin.readline().strip().split()))

def str_arr():
	return list(map(str, sys.stdin.readline().strip().split()))

def input():
	return sys.stdin.readline().strip()
for _ in range(int(input())):
	arr = [i for i in input()]
	st = input()
	a = []
	b = []
	c = []
	rem = []
	arr.sort()
	for i in arr:
		if i == 'a':
			a.append('a')
		elif i == 'b':
			b.append('b')
		elif i == 'c':
			c.append('c')
		else:
			rem.append(i)
	rem.sort()
	if st != 'abc':
		print(*arr, sep='')
	elif len(a) > 0 and len(b) > 0 and (len(c) > 0):
		z = []
		z += a
		z += c
		z += b
		z += rem
		print(*z, sep='')
	else:
		print(*arr, sep='')


from collections import defaultdict
tc = int(input())
for _ in range(tc):
	s = input()
	t = input()
	count_dict = defaultdict(int)
	for c in sorted(set(s)):
		count_dict[c] = s.count(c)
	need = ''
	flag = False
	for c in t:
		if c not in s:
			flag = True
			break
	need = ''
	answer = ''
	if flag:
		print(''.join(sorted(s)))
	else:
		if t[0] == 'a':
			need = 'a' + t[2] + t[1]
		else:
			need = 'abc'
		for c in need:
			count = count_dict[c]
			while count != 0:
				count -= 1
				answer += c
			del count_dict[c]
		for c in count_dict:
			count = count_dict[c]
			while count != 0:
				count -= 1
				answer += c
		print(answer)


n = int(input())
for _ in range(n):
	s = input()
	t = input()
	ss = sorted(s)
	if t == 'abc':
		if 'a' in ss and 'b' in ss and ('c' in ss):
			bl = ss.index('b')
			br = ss.index('c')
			cl = br
			cr = ''.join(ss).rfind('c') + 1
			ss = ss[:bl] + ss[cl:cr] + ss[bl:br] + ss[cr:]
	print(''.join(ss))


import sys, os
import math
if os.path.exists('in.txt'):
	sys.stdin = open('in.txt', 'r')
from io import BytesIO, IOBase
from heapq import *
from bisect import *
from collections import *

def main():
	for _ in range(mi()):
		s = input()
		x = Counter(s)
		t = input()
		if t[0] != 'a':
			print(''.join(sorted(s)))
		else:
			if 'a' not in x:
				print(''.join(sorted(s)))
				continue
			if t[1] == 'b':
				f = 'a' * x['a'] + 'c' * x['c'] + 'b' * x['b']
				for i in range(3, 26):
					f += chr(ord('a') + i) * x[chr(ord('a') + i)]
				print(f)
			else:
				f = 'a' * x['a'] + 'b' * x['b'] + 'c' * x['c']
				for i in range(3, 26):
					f += chr(ord('a') + i) * x[chr(ord('a') + i)]
				print(f)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def MI():
	return map(int, input().split())

def mi():
	return int(input())

def outP(var):
	sys.stdout.write(str(var) + '\n')
MOD = 10 ** 9 + 7
mod = 998244353
main()


import sys, os, io
import math
import bisect
t = int(input())
for a0 in range(t):
	s = input()
	t = input()
	f = 0
	for i in t:
		if i == 'b':
			f = 1
			break
		elif i == 'c':
			break
	s = list(s)
	s.sort()
	cb = 0
	cc = 0
	if t == 'abc' and 'a' in s:
		for i in s:
			if i == 'b':
				cb += 1
			elif i == 'c':
				cc += 1
		res = ''
		if 'a' in s:
			res += s.count('a') * 'a'
		res += cc * 'c'
		res += cb * 'b'
		for i in s:
			if i == 'a' or i == 'b' or i == 'c':
				pass
			else:
				res += i
		print(res)
	else:
		print(''.join(s))


t = int(input())
for tt in range(t):
	s = list(input())
	t = input()
	s.sort()
	ans = ''.join(s)
	if t == 'abc':
		a = s.count('a')
		b = s.count('b')
		c = s.count('c')
		if a > 0 and b > 0 and (c > 0):
			ans = 'a' * a + 'c' * c + 'b' * b + ans[a + b + c:]
	print(ans)


from collections import Counter
t = int(input())
for _ in range(t):
	S = input()
	T = input()
	cnt = Counter(S)
	x = sorted(cnt.items(), key=lambda x: x[0])
	ans = ''
	if T == 'abc' and 'a' in S and ('b' in S) and ('c' in S):
		ans += 'a' * cnt['a']
		ans += 'c' * cnt['c']
		ans += 'b' * cnt['b']
	for i in range(len(x)):
		if x[i][0] in ans:
			continue
		else:
			ans += x[i][0] * x[i][1]
	print(ans)


from __future__ import print_function
from math import *
from collections import deque
import os
import sys
from io import BytesIO, IOBase

def main():
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
mod = 10 ** 9 + 7

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s)])

def invr():
	return map(int, input().split())
for _ in range(inp()):
	s = insr()
	t = input()
	s.sort()
	if t == 'abc' and s.count('a') != 0 and (s.count('b') != 0) and (s.count('c') != 0):
		k = ['a'] * s.count('a')
		k.extend('c' * s.count('c'))
		for i in s:
			if i != 'a' and i != 'c':
				k.append(i)
		print(''.join((i for i in k)))
	else:
		print(''.join((i for i in s)))


n = int(input())
for i in range(n):
	s = ''.join(sorted(list(input())))
	t = input()
	if len(s) <= 2:
		print(s)
	elif t == 'abc':
		if not 'a' in s or not 'b' in s or (not 'c' in s):
			print(s)
		else:
			l = s.find('b')
			r = s.find('c') + s.count('c')
			print(s[:l] + s[r - 1:l - 1:-1] + s[r:])
	else:
		print(s)


def forbiddenSubsequence(s, t):
	s = list(s)
	t = list(t)
	n = len(s)
	s.sort()
	ans = []
	for x in t:
		if x not in s:
			return s
	else:
		if t == ['a', 'b', 'c']:
			ccount = 0
			for x in s:
				if x == 'c':
					ccount += 1
				else:
					ans.append(x)
			for x in range(len(ans)):
				if ans[x] == 'b':
					break
			p = ans[:x] + ['c'] * ccount + ans[x:]
			return p
		else:
			return s
t = int(input())
for _ in range(t):
	s = input()
	t = input()
	print(''.join(forbiddenSubsequence(s, t)))


t = int(input())
for i in range(t):
	s = input()
	t = input()
	l1 = []
	if t != 'abc':
		for i in s:
			l1.append(i)
		l1 = sorted(l1)
		j = ''
		j = j.join(l1)
		print(j)
	else:
		a1 = []
		a2 = []
		a3 = []
		a4 = []
		for i in s:
			if i == 'a':
				a1.append(i)
			elif i == 'b':
				a2.append(i)
			elif i == 'c':
				a3.append(i)
			else:
				a4.append(i)
		a4 = sorted(a4)
		v = ''
		if len(a1) > 0 and len(a2) > 0 and (len(a3) > 0):
			for i in a1:
				v = v + i
			for i in a3:
				v = v + i
			for i in a2:
				v = v + i
			if len(a4) > 0:
				for i in a4:
					v = v + i
		else:
			w = []
			if len(a1) > 0:
				w.extend(a1)
			if len(a2) > 0:
				w.extend(a2)
			if len(a3) > 0:
				w.extend(a3)
			if len(a4) > 0:
				w.extend(a4)
			v = v.join(w)
		print(v)


t = int(input())
for _ in range(t):
	from collections import Counter
	target_count = 3
	target_string = 'abc'
	string_s = input()
	string_t = input()
	counter = Counter(string_s)
	sorted_counter = sorted(counter.items())
	if len(sorted_counter) < target_count or sorted_counter[2][0] != 'c' or sorted_counter[0][0] != 'a' or (sorted_counter[1][0] != 'b'):
		ans = [x * y for (x, y) in sorted_counter]
		ans = ''.join(ans)
		print(ans)
		continue
	if string_t == target_string:
		if len(sorted_counter) > target_count:
			ans = [sorted_counter[0], sorted_counter[2], sorted_counter[1]] + sorted_counter[3:]
		else:
			ans = [sorted_counter[0], sorted_counter[2], sorted_counter[1]]
		ans = [x * y for (x, y) in ans]
		ans = ''.join(ans)
		print(ans)
	else:
		ans = [x * y for (x, y) in sorted_counter]
		ans = ''.join(ans)
		print(ans)


from sys import stdin

def solve():
	for _ in range(int(stdin.readline().strip())):
		S = sorted(list(stdin.readline().rstrip()))
		T = stdin.readline().rstrip()
		s = ''.join(S)
		if T != 'abc' or s.find('a') == -1 or s.find('b') == -1 or (s.find('c') == -1):
			print(s)
			continue
		ans = 'a' * s.count('a') + 'c' * s.count('c') + 'b' * s.count('b')
		for x in s:
			if x not in {'a', 'b', 'c'}:
				ans += x
		print(ans)
solve()


for j in range(int(input())):
	st = input()
	t = input()
	li = list(t)
	dic = {'a': 0, 'b': 0, 'c': 0}
	dic['a'] = st.count('a')
	dic['b'] = st.count('b')
	dic['c'] = st.count('c')
	ans = ''
	ans += 'a' * dic['a']
	if t.index('a') == 0 and 'a' in st:
		ans += t[2] * dic[t[2]]
		ans += t[1] * dic[t[1]]
	else:
		ans += 'b' * dic['b']
		ans += 'c' * dic['c']
	lis = []
	for ch in st:
		if ch != 'a' and ch != 'b' and (ch != 'c'):
			lis.append(ch)
	lis.sort()
	temp = ''.join(lis)
	print(ans + temp)


def solve(s, t):
	s = list(s)
	if t != 'abc' or 'a' not in s or 'b' not in s or ('c' not in s):
		s.sort()
	else:
		a_count = s.count('a')
		b_count = s.count('b')
		c_count = s.count('c')
		f_s = [j for j in s if j not in 'abc']
		f_s.sort()
		s = ['a'] * a_count + ['c'] * c_count + ['b'] * b_count + f_s
	return ''.join(s)

def main():
	ans = []
	t = int(input())
	for _ in range(t):
		s = input()
		t = input()
		ans.append(solve(s, t))
	for a in ans:
		print(a)
main()


q = int(input())
ans = []
for _ in range(q):
	s = list(input().rstrip())
	t = list(input().rstrip())
	s.sort()
	if ''.join(t) == 'abc':
		(sa, sb, sc) = (s.count('a'), s.count('b'), s.count('c'))
		if min(sa, sb, sc):
			(l, r) = (sa, sa + sb + sc)
			j = r - 1
			for i in range(l, r):
				if i >= j:
					break
				(s[i], s[j]) = (s[j], s[i])
				j -= 1
	print(''.join(s))


t = int(input())
for i in range(0, t):
	s = input()
	T = input()
	ss = ''.join(sorted(s))
	lt = []
	for j in range(0, 3):
		lt.append(T[j])
	ls = []
	ls.append(ss[0])
	for j in range(1, len(s)):
		if ls[-1] != ss[j]:
			ls.append(ss[j])
	ls.sort()
	flag = 0
	for j in range(0, len(ls) - 1):
		if lt == ls[j:j + 3]:
			flag = 1
	if flag == 0:
		print(ss)
	else:
		s_lt_m = -1
		s_lt_l = -1
		s_lt_l_l = -1
		for j in range(0, len(ss)):
			if ss[j] == lt[1] and s_lt_m == -1:
				s_lt_m = j
			if ss[j] == lt[2] and s_lt_l == -1:
				s_lt_l = j
			if ss[j] > lt[2]:
				s_lt_l_l = j - 1
				break
		if s_lt_l_l == -1:
			s_lt_l_l = len(ss) - 1
			final_string = ss[0:s_lt_m] + lt[2] * (s_lt_l_l - s_lt_l + 1) + ss[s_lt_m:s_lt_l]
			print(final_string)
		else:
			final_string = ss[0:s_lt_m] + lt[2] * (s_lt_l_l - s_lt_l + 1) + ss[s_lt_m:s_lt_l] + ss[s_lt_l_l + 1:len(ss)]
			print(final_string)


for i in range(int(input())):
	(s, t) = (input(), input())
	List = [j * s.count(j) for j in sorted(set(list(s)))]
	if t == 'abc':
		if 'a' in s and 'b' in s and ('c' in s):
			print(''.join([List[0] + len(List[2]) * 'c' + len(List[1]) * 'b' + ''.join(List[3:])]))
		else:
			print(''.join(List))
	else:
		print(''.join(List))


answers = []
for _ in range(int(input())):
	inp = input()
	t = input()
	if t == 'abc':
		o = {x: 0 for x in inp}
		for (i, c) in enumerate(sorted(inp)):
			o[c] += 1
		if o.get('b') and o.get('c') and o.get('a'):
			new_string = ''
			if o.get('a'):
				new_string += 'a' * o.get('a')
				del o['a']
			new_string += 'c' * o.get('c')
			new_string += 'b' * o.get('b')
			p = ''
			for item in inp:
				if item not in ['a', 'b', 'c']:
					p += item
			ans = new_string + ''.join(sorted(p))
		else:
			ans = ''.join(sorted(inp))
	else:
		ans = ''.join(sorted(inp))
	answers.append(ans)
	print(ans)


for t in range(int(input())):
	s = input()
	s = sorted(s)
	(a, b, c) = input()
	if a not in s or b not in s or c not in s:
		print(''.join(s))
	elif a + b + c != 'abc':
		print(''.join(s))
	else:
		b = -1
		if 'b' in s:
			b = s.index('b')
		if 'c' in s and b != -1:
			A = s.count('a')
			B = s.count('b')
			C = s.count('c')
			ss = ''.join(s)
			ss = ss.replace('a', '')
			ss = ss.replace('b', '')
			ss = ss.replace('c', '')
			print('a' * A + 'c' * C + 'b' * B + ss)


import bisect
mod = 10 ** 9 + 7
eps = 10 ** (-9)

def __gcd(a, b):
	return a if b == 0 else __gcd(b, a % b)

def __lcm(a, b):
	return a * b / __gcd(a, b)

def __fact(n):
	return 1 if n == 1 else n * __fact(n - 1)

def __mex(a):
	mex = 0
	a.sort()
	for x in a:
		if x <= mex:
			mex += 1
		else:
			break
	return mex

def __dist(x1, y1, x2, y2):
	return (x1 - x2) ** 2 + (y1 - y2) ** 2

def __getprimes(n):
	isprime = [True for i in range(n + 1)]
	primes = []
	for i in range(2, n + 1):
		if isprime[i]:
			for j in range(i * i, n + 1, i):
				isprime[j] = False
	for i in range(2, n + 1):
		if isprime[i]:
			primes.append(i)
	return primes

def __modInverse(a, m):
	m0 = m
	y = 0
	x = 1
	if m == 1:
		return 0
	while a > 1:
		q = a // m
		t = m
		m = a % m
		a = t
		t = y
		y = x - q * y
		x = t
	if x < 0:
		x = x + m0
	return x

def __isprime(n):
	if n < 2:
		return False
	i = 2
	while i * i <= n:
		if n % i == 0:
			return False
		i += 1
	return True

def __cntprimediv(n):
	ret = 0
	x = n
	i = 2
	while i * i <= x:
		while n % i == 0:
			n //= i
			ret += 1
		i += 1
	if n > 1:
		ret += 1
	return ret

def __primefactors(n):
	ret = []
	x = n
	i = 2
	while i * i <= x:
		while n % i == 0:
			ret.append(i)
			n //= i
		i += 1
	if n > 1:
		ret.append(n)
	return ret

def __sumdigit(n):
	ret = 0
	while n > 0:
		ret += n % 10
		n //= 10
	return ret

def __zfunc(s):
	n = len(s)
	z = [0 for i in range(n)]
	l = 0
	r = 0
	for i in range(1, n):
		if r >= i:
			z[i] = min(z[i - l], r - i + 1)
		while z[i] + i < n and s[z[i]] == s[z[i] + i]:
			z[i] += 1
		if i + z[i] - 1 > r:
			l = i
			r = i + z[i] - 1
	return z

def __to(n, x):
	ret = ''
	while n > 0:
		q = n % x
		if q < 10:
			ret += str(q)
		else:
			ret += chr(q - 10 + ord('a'))
		n //= x
	return ret[::-1]

def solve(t):
	s = list(input())
	t = list(input())
	s.sort()
	j = 0
	for i in range(len(s)):
		if j < len(t) and s[i] == t[j]:
			j += 1
	if j == len(t):
		cntb = 0
		cntc = 0
		ans = ''
		for c in s:
			if c == 'b':
				cntb += 1
			elif c == 'c':
				cntc += 1
		ss = 'c' * cntc + 'b' * cntb
		for i in range(len(s)):
			if s[i] != 'b' and s[i] != 'c':
				ans += s[i]
			else:
				ans += ss
				ss = ''
		s = list(ans)
	print(''.join(s))
t = 1
t = int(input())
for i in range(t):
	solve(i + 1)


t = int(input())
for _ in range(t):
	s = list(input())
	s.sort()
	s = ''.join(s)
	x = input()
	a = s.count('a')
	b = s.count('b')
	c = s.count('c')
	if x != 'abc' or a * b * c == 0:
		print(s)
	else:
		l = len(s)
		print(a * 'a' + c * 'c' + b * 'b' + s[a + b + c:l])


from collections import defaultdict
tt = int(input())
for _ in range(tt):
	s = input()
	t = input()
	if t == 'abc' and 'a' in s and ('b' in s) and ('c' in s):
		f = defaultdict(int)
		for i in s:
			f[i] += 1
		ans = ''
		ans += 'a' * f['a']
		del f['a']
		ans += 'c' * f['c']
		del f['c']
		ans += 'b' * f['b']
		del f['b']
		for i in sorted(f):
			ans += i * f[i]
		print(ans)
	else:
		print(''.join(sorted(s)))


from collections import Counter
from sys import *
from collections import defaultdict as dd
from math import *

def inp():
	return int(stdin.readline().strip())

def vinp():
	return map(int, stdin.readline().strip().split())

def linp():
	return list(map(int, stdin.readline().strip().split()))

def sinp(n=1):
	if n == 1:
		return stdin.readline().strip()
	elif n == 2:
		return list(stdin.readline().strip())
	else:
		return list(stdin.readline().split())

def pr(*x, end='\n'):
	print(*x, end=end)

def mod(f, val=1000000007):
	return f % val

def csort(c):
	sorted(c.items(), key=lambda pair: pair[1], reverse=True)

def indc(l, n):
	c = {}
	for i in range(n):
		c[l[i]] = c.get(l[i], []) + [i + 1]
	return c
cou = inp()
for _ in range(cou):
	s = sinp(2)
	s2 = sinp(2)
	c = dd(int)
	for i in s:
		c[i] += 1
	k = list(c.keys())
	k.sort()
	t2 = sorted(s2)
	if t2 == s2 and c['a'] >= 1 and (c['b'] >= 1) and (c['c'] >= 1):
		t = ''
		for i in k:
			if i != 'b' and i != 'c':
				t += i * c[i]
			elif i == 'c':
				t += i * c[i]
				t += 'b' * c['b']
		pr(t)
	else:
		k = sorted(s)
		for i in k:
			pr(i, end='')
		pr()


import sys
from math import sqrt, gcd
from collections import deque
sys.setrecursionlimit(10 ** 8)
I = lambda : int(input())
S = lambda : input().strip()
M = lambda : map(int, input().strip().split())
L = lambda : list(map(int, input().strip().split()))
mod = 1000000007

def change(i):
	if t == 'abc':
		(s[i + 1], s[i + 2]) = (s[i + 2], s[i + 1])
	else:
		(s[i], s[i + 1], s[i + 2]) = ('a', 'b', 'c')
for i in range(I()):
	s = list(S())
	t = S()
	s.sort()
	n = len(s)
	if n < 3 or t != 'abc':
		print(''.join(s))
		continue
	if s.count('a') == 0 or s.count('b') == 0 or s.count('c') == 0:
		print(''.join(s))
		continue
	ans = []
	b = 0
	c = 0
	i = 0
	while i < n and s[i] not in ['b', 'c']:
		ans.append(s[i])
		i += 1
	while i < n and s[i] == 'b':
		b += 1
		i += 1
	while i < n and s[i] == 'c':
		c += 1
		i += 1
	ans.append('c' * c + 'b' * b)
	while i < n:
		ans.append(s[i])
		i += 1
	print(''.join(ans))


from collections import defaultdict
from collections import defaultdict, Counter, deque
from sys import stdin, stdout, setrecursionlimit
from math import *
from bisect import bisect_left, bisect_right
from statistics import mode
from functools import reduce
import operator as op
I = lambda : stdin.readline().rstrip('\r\n')
ari = lambda : list(map(int, I().split()))
ars = lambda : list(map(str, I().split()))
arf = lambda : list(map(float, I().split()))
mpi = lambda : map(int, I().split())
mps = lambda : map(str, I().split())
mpf = lambda : map(float, I().split())
mod = 10 ** 9 + 7
setrecursionlimit(10 ** 8)
inf = float('inf')

def power(A, B, p):
	res = 1
	A = A % p
	if A == 0:
		return 0
	while B > 0:
		if B & 1 == 1:
			res = res * A % p
		B = B >> 1
		A = A * A % p
	return res

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	for i in range(5, ceil(sqrt(n)) + 1, 6):
		if n % i == 0 or n % (i + 2) == 0:
			return False
	return True

def nearest2(num):
	return int(pow(2, int(log(num, 2))))

def comb(n, r):
	r = min(r, n - r)
	if r < 0:
		return 0
	numer = reduce(op.mul, range(n, n - r, -1), 1)
	denom = reduce(op.mul, range(1, r + 1), 1)
	return numer // denom
for t1 in range(int(input())):
	S1 = input()
	T1 = input()
	ans1 = ''
	D1 = defaultdict(int)
	for i in S1:
		D1[i] += 1
	if 0 in [D1['a'], D1['b'], D1['c']]:
		print(''.join(sorted(S1)))
	else:
		if T1 == 'abc':
			for i in S1:
				if i == 'a':
					ans1 += i
			for i in S1:
				if i == 'c':
					ans1 += i
			for i in S1:
				if i == 'b':
					ans1 += i
		else:
			for i in S1:
				if i == 'a':
					ans1 += i
			for i in S1:
				if i == 'b':
					ans1 += i
			for i in S1:
				if i == 'c':
					ans1 += i
		temp2 = ''
		for i in S1:
			if i not in T1:
				temp2 += i
		ans1 += ''.join(sorted(temp2))
		print(ans1)


cases = int(input())
for i in range(cases):
	S = input()
	T = input()
	S1 = sorted(S)
	flag = False
	for item in T:
		if item not in S1:
			flag = True
			break
	if T[0] != 'a' or T[2] != 'c':
		flag = True
	if flag:
		print(''.join(S1))
	else:
		countb = 0
		tempb = 0
		countc = 0
		for (j, item) in enumerate(S1):
			if item == 'a':
				continue
			elif item == 'b':
				if countb == 0:
					tempb = j
				countb += 1
			elif item == 'c':
				countc += 1
			else:
				break
		for i in range(countc + countb):
			if countc > 0:
				S1[tempb + i] = 'c'
				countc -= 1
			else:
				S1[tempb + i] = 'b'
		print(''.join(S1))


kl = int(input())
for kkl in range(kl):
	str = input()
	t = input()
	sp = list(str)
	sp.sort()
	sp.append(1)
	i = 0
	if 'a' in sp and 'b' in sp and ('c' in sp) and (t == 'abc'):
		while sp[i] == 'a':
			i += 1
		ka = i
		while sp[i] == 'b':
			i += 1
		kb = i
		while sp[i] == 'c' and i < len(sp):
			i += 1
		if i == len(sp):
			i += 1
		t = min(kb - ka, i - kb)
		(sp[ka:ka + t], sp[i - t:i]) = (['c'] * t, ['b'] * t)
	for i in range(len(sp) - 1):
		print(sp[i], end='')
	print()


Entrada = int(input())
while Entrada:
	Entrada -= 1
	string1 = list(input())
	String2 = input()
	resultado = {}
	for i in string1:
		try:
			resultado[i] += 1
		except:
			resultado[i] = 1
	if String2 in ['bca', 'cba', 'cab', 'bac', 'acb']:
		mode = 0
	elif String2 == 'abc':
		mode = 1
	if 'a' not in resultado.keys() or 'b' not in resultado.keys() or 'c' not in resultado.keys():
		saida = ''
		for x in sorted(resultado.keys()):
			saida += x * resultado[x]
		print(saida)
	else:
		saida = ''
		if mode == 1:
			saida += 'a' * resultado['a'] + 'c' * resultado['c'] + 'b' * resultado['b']
			del resultado['a']
			del resultado['b']
			del resultado['c']
		for x in sorted(resultado.keys()):
			saida += x * resultado[x]
		print(saida)


t = int(input())
for p in range(t):
	s = list(input())
	a = input()
	s.sort()
	if a == 'abc':
		if 'a' in s and 'b' in s and ('c' in s):
			for i in range(len(s)):
				if s[i] == 'b':
					s[i] = 'ab'
				if s[i] == 'c':
					s[i] = 'aac'
			s.sort()
			for i in range(len(s)):
				if s[i] == 'ab':
					s[i] = 'b'
				if s[i] == 'aac':
					s[i] = 'c'
	print(''.join(s))


for i in range(int(input())):
	arr = list(input())
	t = input()
	arr.sort()
	ca = arr.count('a')
	cb = arr.count('b')
	cc = arr.count('c')
	if t == 'abc':
		if ca == 0:
			pass
		else:
			for l in range(cc):
				arr[ca + l] = 'c'
			for l in range(cb):
				arr[ca + cc + l] = 'b'
		result = ''.join(arr)
	else:
		result = ''.join(arr)
	print(result)


import sys, math, heapq, queue
from collections import deque
from functools import cmp_to_key
fast_input = sys.stdin.readline
MOD = 998244353
for _ in range(int(fast_input())):
	s = input()
	t = input()
	count = [0] * 26
	for i in s:
		count[ord(i) - ord('a')] += 1
	res = ''
	if t[0] == 'a' and count[0] != 0 and (count[1] != 0) and (count[2] != 0):
		res = 'a' * count[0] + t[2] * count[ord(t[2]) - ord('a')] + t[1] * count[ord(t[1]) - ord('a')]
	else:
		res = 'a' * count[0] + 'b' * count[1] + 'c' * count[2]
	for i in range(3, 26):
		res += chr(ord('a') + i) * count[i]
	print(res)


T = int(input())
for t in range(T):
	s1 = input()
	s1 = sorted(s1)
	s3 = ''
	for i in s1:
		s3 += i
	s2 = input()
	(a, b, c) = (0, 0, 0)
	temp = ''
	for i in s1:
		if i == 'a':
			a += 1
		elif i == 'b':
			b += 1
		elif i == 'c':
			c += 1
		else:
			temp += i
	if a == 0 or b == 0 or c == 0:
		print(s3)
		continue
	if s2[0] == 'b' or s2[0] == 'c':
		res = s3
	elif s2[1] == 'b':
		res = a * 'a' + c * 'c' + b * 'b' + temp
	else:
		res = a * 'a' + b * 'b' + c * 'c' + temp
	print(res)


def fn():
	res = []
	for i in range(int(input())):
		s = input()
		p = input()
		_dict = dict()
		for ch in s:
			if ch in _dict:
				_dict[ch] += 1
			else:
				_dict[ch] = 1
		_str = ''
		if 'b' in _dict and 'c' in _dict and (p == 'abc'):
			if _dict.get('a'):
				_b = 'b' * _dict.pop('b')
				_c = 'c' * _dict.pop('c')
			else:
				_b = _c = ''
			for i in range(97, 97 + 26):
				ch = chr(i)
				cnt = _dict.get(ch, 0)
				if ch == 'a':
					cnt = cnt
					_all = ch * cnt + _c + _b
					_str = _str + _all
				else:
					_all = ch * cnt
					_str = _str + _all
		else:
			for i in range(97, 97 + 26):
				ch = chr(i)
				cnt = _dict.get(ch, 0)
				_all = ch * cnt
				_str = _str + _all
		res.append(_str)
	print(*res, sep='\n')
fn()


import sys
inpu = sys.stdin.readline
prin = sys.stdout.write
I = lambda : [*map(int, inpu().split())]
t = I()[0]
for _ in range(t):
	s = [*inpu().strip()]
	t = inpu().strip()
	a = sorted(s)
	ass = a.count('a')
	bss = a.count('b')
	css = a.count('c')
	tot = ass + bss + css
	if t == 'abc' and ass > 0 and (bss > 0) and (css > 0):
		a = ['a'] * ass + ['c'] * css + ['b'] * bss + a[tot:]
	print(''.join(a))


def get_start_end(arr, target):
	s = arr.index(target)
	e = s
	while e < len(arr) and arr[e] == target:
		e += 1
	return (s, e - 1)
t = int(input())
for _ in range(t):
	s = list(input())
	t = input()
	s.sort()
	res = s
	if 'a' in s and 'b' in s and ('c' in s) and (t == 'abc'):
		(bs, be) = get_start_end(s, 'b')
		(cs, ce) = get_start_end(s, 'c')
		res = s[:bs]
		res += s[cs:ce + 1]
		res += s[bs:be + 1]
		res += s[ce + 1:]
	print(''.join(res))


def counter(val):
	d = {'a': 0, 'b': 0, 'c': 0}
	for i in val:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	return d
for i in range(int(input())):
	val = counter(input())
	print(''.join([val.pop(i) * i for i in ('acb' if input() == 'abc' and all([val[i] > 0 for i in 'abc']) else 'abc')] + [val.pop(i) * i for i in sorted(val.keys())]))


for _ in range(int(input())):
	(s, t) = (''.join(sorted(list(input()))), input())
	if t == 'abc' and s.count('a') > 0 and (s.count('b') > 0) and (s.count('c') > 0):
		(p, cnt1, cnt2) = (s.find('b'), s.count('b'), s.count('c'))
		s = s[:p] + 'c' * cnt2 + 'b' * cnt1 + s[p + cnt1 + cnt2:]
	print(s)


t = int(input())
for _ in range(t):
	s = ''.join(sorted(input()))
	t = input()
	aa = s.count('a')
	bb = s.count('b')
	cc = s.count('c')
	if aa and bb and cc and (t == 'abc'):
		print('a' * aa + 'c' * cc + 'b' * bb + s[aa + bb + cc:])
	else:
		print(s)


tc = int(input())
start = 1
while start <= tc:
	s = input()
	t = input()
	if t != 'abc':
		x = ''.join(sorted(s))
		print(x)
	elif t == 'abc' and 'a' not in s:
		x = ''.join(sorted(s))
		print(x)
	else:
		a = ''
		b = ''
		for i in s:
			if i == 'a' or i == 'c':
				a = a + i
			else:
				b = b + i
		x = ''.join(sorted(a))
		y = ''.join(sorted(b))
		print(x + y)
	start += 1


tt = 1
tt = int(input())
for _ in range(tt):
	s = input()
	n = len(s)
	s = list(s)
	s.sort()
	t = input()
	if t == 'abc' and 'a' in s and ('b' in s) and ('c' in s):
		a = []
		c = 0
		for i in s:
			if i == 'a':
				a.append(i)
		for i in s:
			if i == 'c':
				a.append(i)
		for i in s:
			if i != 'a' and i != 'c':
				a.append(i)
		print(*a, sep='')
	else:
		print(*s, sep='')


for test in range(int(input())):
	s = input()
	t = input()
	ans = ''
	s = list(s)
	s.sort()
	if t == 'abc' and s.count('a') != 0 and (s.count('b') != 0) and (s.count('c') != 0):
		ans += s.count('a') * 'a'
		ans += s.count('c') * 'c'
		ans += s.count('b') * 'b'
		for i in range(len(s)):
			if s[i] != 'a' and s[i] != 'b' and (s[i] != 'c'):
				ans += s[i]
	else:
		ans = ''.join(s)
	print(ans)


from collections import defaultdict
import sys
input = sys.stdin.readline
flush = sys.stdout.flush
get_int = lambda : int(input().rstrip())
get_arr = lambda : [int(w) for w in input().split()]
t = get_int()

def func(c):
	if c == 'b':
		return 2
	elif c == 'c':
		return 1
	else:
		return ord(c) - ord('a')
for _ in range(t):
	s = input().rstrip()
	t = input().rstrip()
	if t == 'abc' and 'a' in s:
		print(''.join(sorted(s, key=func)))
	else:
		print(''.join(sorted(s)))


problem_num = int(input())
for i in range(problem_num):
	S = input()
	T = input()
	if T == 'abc' and 'a' in S and ('b' in S) and ('c' in S):
		S = ''.join(sorted(S))
		b = S.count('b')
		c = S.count('c')
		if len(S) > S.index('c') + c:
			S = S[:S.index('b')] + 'c' * c + 'b' * b + S[S.index('c') + c:]
		else:
			S = S[:S.index('b')] + 'c' * c + 'b' * b
		print(S)
	else:
		print(''.join(sorted(S)))


for i in range(int(input())):
	s = list(input().strip())
	s.sort()
	s1 = input()
	if 'a' not in s or 'b' not in s or 'c' not in s:
		print(*s, sep='')
	elif s1 != 'abc':
		print(*s, sep='')
	else:
		for i in range(s.count('a')):
			print('a', end='')
		for i in range(s.count('c')):
			print('c', end='')
		for el in s:
			if el not in 'ac':
				print(el, end='')
		print()


loop = int(input())
for _ in range(loop):
	lista = sorted(input())
	seq = input()
	lista = ''.join(lista)
	if 'a' in lista and 'b' in lista and ('c' in lista) and (seq == 'abc'):
		abc = lista.count('a') + lista.count('b') + lista.count('c')
		print('a' * lista.count('a') + 'c' * lista.count('c') + 'b' * lista.count('b') + lista[abc:])
	else:
		print(lista)


for _ in range(int(input())):
	s = input()
	t = input()
	s = list(s)
	s = sorted(s)
	if 'a' not in s or 'b' not in s or 'c' not in s:
		ans = sorted(s)
		ans = ''.join(s)
		print(ans)
	elif t[0] == 'c' or t[1] == 'c' or t[0] == 'b':
		ans = ''.join(s)
		print(ans)
	else:
		ans = ''
		for i in s:
			if i == 'a' or i == 'c':
				ans += i
		for i in s:
			if i not in ['a', 'c']:
				ans += i
		print(ans)


T = int(input())
for x in range(T):
	S = list(input())
	C = input()
	if C != 'abc':
		print(''.join(sorted(S)))
	elif 'a' not in S or 'b' not in S or 'c' not in S:
		print(''.join(sorted(S)))
	else:
		S = sorted(S)
		temp = []
		done = False
		cc = 0
		bc = 0
		for c in S:
			if c > 'c' and (not done):
				for a in range(cc):
					temp.append('c')
				for a in range(bc):
					temp.append('b')
				done = True
			if c == 'c':
				cc += 1
			elif c == 'b':
				bc += 1
			else:
				temp.append(c)
		if not done:
			for a in range(cc):
				temp.append('c')
			for a in range(bc):
				temp.append('b')
		print(''.join(temp))


for k in range(int(input())):
	s = sorted(list(input()))
	t = input()
	if 'a' in s and 'b' in s and ('c' in s) and (t == 'abc'):
		i2 = s.index('b')
		s = ''.join(s)
		i3 = s.count('a') + s.count('b') + s.count('c')
		s = 'a' * s.count('a') + 'c' * s.count('c') + 'b' * s.count('b') + s[i3:]
	else:
		s = ''.join(s)
	print(s)


import bisect
import collections
import itertools
import math
import sys
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.buffer.readline())

def MI():
	return map(int, sys.stdin.buffer.readline().split())

def LI():
	return list(map(int, sys.stdin.buffer.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def BI():
	return sys.stdin.buffer.readline().rstrip()

def SI():
	return sys.stdin.buffer.readline().rstrip().decode()

def li():
	return [int(i) for i in input().split()]

def lli(rows):
	return [li() for _ in range(rows)]

def si():
	return input()

def ii():
	return int(input())

def ins():
	return input().split()

def drank(d, processing, da, rank):
	tmp = 10 ** 9
	if len(d[da]) == 1:
		return 1
	for di in d[da]:
		if processing[di - 1] == 0:
			processing[di - 1] = 1
			tmp = min(tmp, drank(d, processing, di, rank))
			processing[di - 1] = 0
	rank[da - 1] = tmp + 1
	return tmp + 1

def binary_search(n, a):
	l = len(a)
	low = 0
	high = l - 1
	while high >= low:
		mid = (high + low) // 2
		if a[mid] == n:
			return mid
		elif a[mid] > n:
			high = mid - 1
		else:
			low = mid + 1
	return -1
is_prime = [True] * (10 ** 6 + 1)

def primeseive(n):
	is_prime[0] = is_prime[1] = False
	i = 2
	while i * i <= n:
		if is_prime[i] == True:
			for j in range(i * i, n + 1, i):
				is_prime[j] = False
		i += 1

def solve():
	s = sorted(list(si()))
	t = si()
	if 'a' not in s or 'b' not in s or 'c' not in s:
		return ''.join(s)
	if t[0] != 'a':
		return ''.join(s)
	elif t[1] != 'b':
		return ''.join(s)
	else:
		na = s.count('a')
		nb = s.count('b')
		nc = s.count('c')
		return 'a' * na + 'c' * nc + 'b' * nb + ''.join(s[na + nb + nc:])

def main():
	for _ in range(ii()):
		sys.stdout.write(str(solve()) + '\n')
main()


from collections import defaultdict
for _ in range(int(input())):
	s1 = list(input())
	s2 = list(input())
	check = defaultdict(int)
	for i in s1:
		check[i] += 1
	ans = list(check.keys())
	ans = sorted(ans)
	ans2 = sorted(s2)
	if not (ans2 == s2 and check['a'] >= 1 and (check['b'] >= 1) and (check['c'] >= 1)):
		final = sorted(s1)
		for i in final:
			print(i, end='')
		print()
	else:
		final = ''
		for i in ans:
			if not (i != 'b' and i != 'c'):
				pass
			if i != 'b' and i != 'c':
				final += i * check[i]
			elif i == 'c':
				final += i * check[i]
				final += 'b' * check['b']
		print(final)


for i in range(int(input())):
	l = [0] * 26
	s = input()
	for i in s:
		l[ord(i) - 97] += 1
	t = input()
	s2 = ''
	s2 += 'a' * l[0]
	if 'a' in s and t[0] == 'a' and (t.index('b') < t.index('c')):
		s2 += 'c' * l[2]
		s2 += 'b' * l[1]
	else:
		s2 += 'b' * l[1]
		s2 += 'c' * l[2]
	for i in range(3, len(l)):
		s2 += chr(i + 97) * l[i]
	print(s2)


for _ in range(int(input())):
	s = input()
	t = input()
	a = b = c = e = ''
	for i in s:
		if i == 'a':
			a += 'a'
		elif i == 'b':
			b += 'b'
		elif i == 'c':
			c += 'c'
		else:
			e += i
	if a == '' or b == '' or c == '':
		ans = a + b + c + ''.join(sorted(e))
		print(ans)
		continue
	if t[0] != 'a':
		ans = a + b + c + ''.join(sorted(e))
	elif t[1] == 'b':
		ans = a + c + b + ''.join(sorted(e))
	else:
		ans = a + b + c + ''.join(sorted(e))
	print(ans)


n = int(input())
for i in range(n):
	s = input()
	t = input()
	slist = [i for i in s]
	orderedlist = [i for i in s]
	orderedlist.sort()
	slice = ''.join(orderedlist)
	t0c = slice.count(t[0])
	t1c = slice.count(t[1])
	t2c = slice.count(t[2])
	if t[0] in slice and t[1] in slice and (t[2] in slice):
		indext0 = slice.index(t[0])
		indext1 = slice.index(t[1])
		indext2 = slice.index(t[2])
		l = []
		for i in orderedlist:
			if (i, orderedlist.count(i)) in l:
				continue
			else:
				l.append((i, orderedlist.count(i)))
		l2 = tuple((a * b for (a, b) in l))
		l7 = [a * b for (a, b) in l]
		if indext0 < indext1 and indext1 < indext2:
			v = 0
			for i in l2:
				if t[1] in i:
					l7[v] = t[2] * t2c
				elif t[2] in i:
					l7[v] = t[1] * t1c
				v += 1
			print(''.join(l7))
		else:
			print(slice)
	else:
		print(slice)


entrada = int(input())
for t in range(entrada):
	name = sorted(input())
	aux = input()
	if aux == 'abc' and 'b' in name and ('c' in name) and ('a' in name):
		name = ''.join((str(elem) for elem in name))
		x = name.count('a')
		y = name.count('b')
		z = name.count('c')
		result = x + y + z
		name = 'a' * x + 'c' * z + 'b' * y + name[result:]
	else:
		name = ''.join((str(elem) for elem in name))
	print(name)


n = int(input())
while n:
	s = ''.join(sorted(input()))
	t = input()
	a = s.count('a')
	b = s.count('b')
	c = s.count('c')
	if t == 'abc' and 'a' in s and ('b' in s) and ('c' in s):
		print(a * 'a' + c * 'c' + b * 'b' + s[a + b + c:])
	else:
		print(s)
	n -= 1


n = int(input())
while n != 0:
	st = input()
	chk = input()
	x = ''.join(sorted(st))
	s = ''
	if 'a' not in st or 'b' not in st or 'c' not in st:
		print(x)
	elif chk != 'abc':
		print(x)
	else:
		for i in ['a', 'b', 'c']:
			x = x.replace(i, '')
		print(st.count('a') * 'a' + st.count('c') * 'c' + st.count('b') * 'b' + x)
	n -= 1


from typing import Counter
t = int(input())
from collections import Counter
for _ in range(t):
	S = input()
	T = input()
	l = list(S)
	c = Counter(l)
	if T != 'abc':
		l.sort()
		ans = ''.join(l)
	elif 'a' not in c or 'b' not in c or 'c' not in c:
		l.sort()
		ans = ''.join(l)
	else:
		merged = list(c.items())
		merged.sort()
		(merged[1], merged[2]) = (merged[2], merged[1])
		l = []
		for (c1, freq) in merged:
			l.append(c1 * freq)
		ans = ''.join(l)
	print(ans)


t = int(input())
while t > 0:
	s = input()
	T = input()
	if 'a' in s and 'b' in s and ('c' in s) and (T == 'abc'):
		lii = []
		for i in s:
			if i == 'a' or i == 'c':
				continue
			lii.append(i)
		lii.sort()
		an = ''.join(lii)
		ans = '' + 'a' * s.count('a') + 'c' * s.count('c') + an
		print(ans)
		t -= 1
		continue
	li = list(s)
	li.sort()
	print(''.join(li))
	t -= 1


from collections import deque as de
import math
import sys
from math import sqrt as sq
from math import floor as fl
from math import ceil as ce
from sys import stdin, stdout
sys.setrecursionlimit(10 ** 7)
from collections import Counter as cnt
from functools import reduce
from itertools import groupby as gb
from bisect import bisect_left as bl, bisect_right as br
from typing import Coroutine

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

class My_stack:

	def __init__(self):
		self.data = []

	def my_push(self, x):
		return self.data.append(x)

	def my_pop(self):
		return self.data.pop()

	def __iter__(self):
		return iter(self.data)

	def my_peak(self):
		return self.data[-1]

	def my_contains(self, x):
		return self.data.count(x)

	def my_show_all(self):
		return self.data

	def isEmpty(self):
		return len(self.data) == 0

	def len(self):
		return len(self.data)
arrStack = My_stack()

class graph:

	def __init__(self):
		self.graphdict = {}

	def add_edge(self, node, neighbor):
		if node not in self.graphdict:
			self.graphdict[node] = [neighbor]
		else:
			self.graphdict[node].append(neighbor)

	def show_edge(self):
		for node in self.graphdict:
			for neighbors in self.graphdict:
				print(node, neighbors)

	def show_graph(self):
		return self.graphdict

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def binarytodecimal(n):
	return int(n, 2)

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def get_prime_factors(number):
	prime_factors = []
	while number % 2 == 0:
		prime_factors.append(2)
		number = number / 2
	for i in range(3, int(math.sqrt(number)) + 1, 2):
		while number % i == 0:
			prime_factors.append(int(i))
			number = number / i
	if number > 2:
		prime_factors.append(int(number))
	return prime_factors

def get_frequency(list):
	dic = {}
	for ele in list:
		if ele in dic:
			dic[ele] += 1
		else:
			dic[ele] = 1
	return dic

def Log2(x):
	return math.log10(x) / math.log10(2)

def getProduct(n):
	product = 1
	while n != 0:
		product = product * (n % 10)
		n = n // 10
	return product

def regularBracketsequence(str, arrStack):
	for i in range(len(str)):
		if str[i] == '(':
			arrStack.my_push(str[i])
		elif arrStack.isEmpty():
			return False
		else:
			arrStack.my_pop()
	if arrStack.isEmpty():
		return True
	else:
		return False

def lcm(x, y):
	lcm = x * y // math.gcd(x, y)
	return lcm

def isPowerOfTwo(n):
	return math.ceil(Log2(n)) == math.floor(Log2(n))

def checkisap(list):
	d = list[1] - list[0]
	for i in range(2, len(list)):
		temp = list[i] - list[i - 1]
		if temp != d:
			return False
	return True

def primes_method5(n):
	out = {}
	sieve = [True] * (n + 1)
	for p in range(2, n + 1):
		if sieve[p]:
			out[p] = 1
			for i in range(p, n + 1, p):
				sieve[i] = False
	return out

def id(i, j, col):
	ans = (i - 1) * col
	ans += j
	return ans

def getSum(n):
	strr = str(n)
	list_of_number = list(map(int, strr.strip()))
	return sum(list_of_number)

def checkperfectsquare(n):
	if ce(sq(n)) == fl(sq(n)):
		return True
	else:
		return False

def combinatrics(n, r):
	num = n
	deno = n - r
	pr = 1
	for i in range(num, deno, -1):
		pr *= i
	an = 1
	for i in range(1, r + 1):
		an *= i
	ans = pr // an
	return ans

def ceildiv(x, y):
	return (x + y - 1) // y

def di():
	return map(int, input().split())

def ii():
	return int(input())

def li():
	return list(map(int, input().split()))

def si():
	return list(map(str, input()))

def indict():
	dic = {}
	for (index, value) in enumerate(input().split()):
		dic[int(value)] = int(index)
	return dic

def frqdict():
	dic = {}
	for (index, value) in enumerate(input()):
		if value not in dic:
			dic[value] = 1
		else:
			dic[value] += 1
	return dic
t = ii()
while t:
	t -= 1
	s = si()
	ts = input()
	if ts == 'abc':
		ac = s.count('a')
		bc = s.count('b')
		cc = s.count('c')
		s.sort()
		if ac and bc and cc:
			temp = ''.join(s).rfind('c')
			final = 'a' * ac + 'c' * cc + 'b' * bc + ''.join(s[temp + 1:])
			print(final)
		else:
			s.sort()
			print(''.join(s))
	else:
		s.sort()
		print(''.join(s))


from sys import stdin
import math

def main():
	n = int(stdin.readline())
	for i in range(n):
		t = stdin.readline()
		s = stdin.readline()[0:3]
		tmp = sorted(t, key=str.lower)[1:]
		ai = bi = ci = 0
		ap = bp = cp = False
		for u in range(0, len(t) - 1):
			if tmp[u] == 'a':
				ap = True
				ai = u
			if tmp[u] == 'b':
				bp = True
				bi = u
			if tmp[u] == 'c':
				cp = True
				ci = u
		if not ap or not bp or (not cp) or (s != 'abc'):
			for x in tmp:
				print(x, end='')
			print('\n')
			continue
		for x in range(0, ai + 1):
			print(tmp[x], end='')
		for x in range(bi + 1, ci + 1):
			print(tmp[x], end='')
		for x in range(ai + 1, bi + 1):
			print(tmp[x], end='')
		for x in range(ci + 1, len(t) - 1):
			print(tmp[x], end='')
		print('\n')
	return
main()


def solver():
	n = int(input())
	for _ in range(n):
		s = ''.join(sorted(input()))
		t = input()
		final = ''
		if t == 'abc':
			if 'a' in s and 'b' in s and ('c' in s):
				checker = True
				f = len(list(filter(lambda x: x == 'c', s)))
				for a in s:
					if a == 'b' and checker:
						for i in range(f):
							final = final + 'c'
						final = final + 'b'
						checker = False
					elif a == 'c':
						checker = True
					else:
						final = final + a
				print(final)
			else:
				print(s)
		else:
			print(s)
solver()


I = input
for _ in [0] * int(I()):
	s = sorted(I())
	t = I()
	if {*t} <= {*s} and 'abc' == t:
		(i, j) = map(s.index, 'bc')
		j += s.count('c')
		s[i:j] = s[i:j][::-1]
	print(*s, sep='')


for _ in range(int(input())):
	s = input()
	t = input()
	a = ''.join(sorted(s))
	if t == 'abc' and 'a' in s and ('b' in s) and ('c' in s):
		ind = a.rfind('a')
		l = a.count('c')
		a = a.replace('c', '')
		a = a[:ind + 1] + 'c' * l + a[ind + 1:]
		print(a)
	else:
		print(a)


def fun(s, s1):
	if len(s) < len(s1):
		return False
	l = []
	for x in s1:
		if x in s:
			i = s.index(x)
			l.append(i)
		else:
			return False
	l1 = sorted(l)
	if l1 == l:
		return True
	else:
		return False
T = int(input())
for _ in range(T):
	s = input().rstrip()
	t = input().rstrip()
	s2 = ''.join(sorted(s))
	s3 = ''
	if t == 'abc':
		if fun(s2, t):
			idx1 = s2.index('b')
			idx2 = s2.index('c')
			idx3 = idx1
			idx4 = idx2
			for i in range(idx1, idx2):
				if s2[i] == 'b':
					if idx3 < i:
						idx3 = i
			for i in range(idx2, len(s2)):
				if s2[i] == 'c':
					if idx4 < i:
						idx4 = i
				else:
					break
			s3 = s2[0:idx1] + s2[idx2:idx4 + 1] + s2[idx1:idx3 + 1] + s2[idx4 + 1:]
			print(s3)
		else:
			print(s2)
	else:
		print(s2)


from itertools import *

def f(perm, permabc):
	if permabc != 'abc' or 'a' not in perm or 'b' not in perm or ('c' not in perm):
		return ''.join(sorted(perm))
	c = ''.join(sorted(perm, key=lambda x: ord(x) if x not in ('b', 'c') else 98 + 99 - ord(x)))
	return c
a = int(input())
l = []
for i in range(a):
	l.append((input(), input()))
out = []
for i in l:
	out.append(f(i[0], i[1]))
for i in out:
	print(i)


for _ in range(int(input())):
	s = input()
	t = input()
	a = 0
	b = 0
	c = 0
	nm = []
	for i in s:
		if i == 'a':
			a += 1
		elif i == 'b':
			b += 1
		elif i == 'c':
			c += 1
		else:
			nm.append(i)
	ans = 'a' * a
	if t != 'abc' or a == 0 or b == 0 or (c == 0):
		ans += 'b' * b
		ans += 'c' * c
	else:
		ans += 'c' * c + 'b' * b
	ans += ''.join(sorted(nm))
	print(ans)


test = int(input())
for _ in range(test):
	s = input('')
	t = input('')
	letters = dict()
	for i in s:
		letters[i] = letters.get(i, 0) + 1
	sortedletters = sorted(letters.keys())
	ans = ''
	if t == 'abc':
		if letters.get('a'):
			if letters.get('c'):
				skipC = False
				for letter in sortedletters:
					if letter == 'b':
						ans += 'c' * letters['c']
						ans += 'b' * letters['b']
						skipC = True
						continue
					if letter == 'c' and skipC:
						continue
					ans += letter * letters[letter]
			else:
				for letter in sortedletters:
					ans += letter * letters[letter]
		else:
			for letter in sortedletters:
				ans += letter * letters[letter]
	elif t == 'acb':
		for letter in sortedletters:
			ans += letter * letters[letter]
	elif t == 'bac':
		for letter in sortedletters:
			ans += letter * letters[letter]
	elif t == 'bca':
		for letter in sortedletters:
			ans += letter * letters[letter]
	elif t == 'cab':
		for letter in sortedletters:
			ans += letter * letters[letter]
	elif t == 'cba':
		for letter in sortedletters:
			ans += letter * letters[letter]
	print(ans)


t = int(input())
lis = []
for i in range(t):
	s = input()
	T = input()
	if T != 'abc' or s.count('a') == 0 or s.count('b') == 0 or (s.count('c') == 0):
		s1 = ''.join(sorted(s))
		lis.append(s1)
	else:
		s1 = ''.join(sorted(s))
		m = s1.count('b')
		s1 = s1.replace('b', '')
		s1 = s1[:s1.index('c') + s1.count('c')] + 'b' * m + s1[s1.index('c') + s1.count('c'):]
		lis.append(s1)
print(*lis, sep='\n')


for _ in range(int(input())):
	s = input()
	ac = s.count('a')
	bc = s.count('b')
	cc = s.count('c')
	t = input()
	r = ''.join(sorted(s))
	x = ''
	if t == 'abc':
		if ac != 0:
			x += ac * 'a' + cc * 'c' + bc * 'b' + r[ac + bc + cc:]
			print(x)
		else:
			x += bc * 'b' + cc * 'c' + r[ac + bc + cc:]
			print(x)
	else:
		x += ac * 'a' + bc * 'b' + cc * 'c' + r[ac + bc + cc:]
		print(x)


def Myfunc(e):
	if e == 'b':
		return 99
	elif e == 'c':
		return 98
	else:
		return ord(e)
for _ in range(int(input())):
	s = list(input())
	t = input()
	if t == 'abc' and 'a' in s:
		s.sort(key=Myfunc)
	else:
		s.sort()
	print(''.join(s))


def find_next(lista, e, i):
	saida = i
	for j in range(i, len(lista)):
		if lista[j] != e:
			saida = j
			break
	return saida

def resolve(s, t):
	s_List = list(s)
	s_List.sort()
	primeiroElemento = False
	i = find_next(s_List, s_List[0], 0)
	j = find_next(s_List, s_List[i], i)
	if s_List[i] == t[1] and s_List[j] == t[2]:
		if s_List[i - 1] == t[0]:
			while j < len(s_List) and s_List[j] == t[2]:
				aux = s_List[i]
				s_List[i] = s_List[j]
				s_List[j] = aux
				i += 1
				j += 1
	print(''.join(s_List))
num = int(input())
for n in range(num):
	s = input()
	t = input()
	resolve(s, t)


def forbiddenSubsequence(s, t):
	s = s.replace('\r', '')
	t = t.replace('\r', '')
	s = [i for i in s]
	s.sort()
	if t != 'abc':
		return ''.join(s)
	for i in t:
		if i not in s:
			return ''.join(s)
	i = s.index('b')
	j = len(s) - s[::-1].index('c') - 1
	while i < j:
		(s[i], s[j]) = (s[j], s[i])
		i += 1
		j -= 1
	return ''.join(s)
for _ in range(int(input())):
	s = input()
	t = input()
	print(forbiddenSubsequence(s, t))


for _ in range(int(input())):
	s = input()
	t = input()
	if 'a' not in s or 'b' not in s or 'c' not in s:
		s = ''.join(sorted(s))
		print(s)
	elif t != 'abc':
		s = ''.join(sorted(s))
		print(s)
	else:
		s = sorted(s)
		cnt_a = s.count('a')
		cnt_b = s.count('b')
		cnt_c = s.count('c')
		ans = 'a' * cnt_a + 'c' * cnt_c + 'b' * cnt_b
		s = ''.join(s)
		ans += s[cnt_a + cnt_b + cnt_c:]
		print(ans)


for _ in range(int(input())):
	s = list(input())
	t = input()
	if t == 'abc':
		s = ''.join(sorted(s))
		i_c = s.count('c')
		i_b = s.count('b')
		print(s.replace('a' + 'b' * i_b + 'c' * i_c, 'a' + 'c' * i_c + 'b' * i_b))
	else:
		print(''.join(sorted(s)))


x = int(input())
for z in range(x):
	(s, t) = (input(), input())
	s = ''.join(sorted(s))
	r = s
	r = ''.join(dict.fromkeys(r))
	if not r.find(t) != -1:
		print(s)
	else:
		n = s.count('c')
		c = 'c' * n
		s = s.replace('c', '')
		i = s.find('b')
		print(s[0:i] + c + s[i:])


for _ in range(int(input())):
	line = ''.join(sorted(input()))
	t = input()
	if t == 'abc' and all((x in line for x in 'abc')):
		temp = line.count('c')
		line = line.replace('c', 'b')
		print(line.replace('b', 'c', temp))
	else:
		print(line)


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
sys.setrecursionlimit(100000000)
inp = lambda : int(input())
strng = lambda : input().strip()
jn = lambda x, l: x.join(map(str, l))
strl = lambda : list(input().strip())
mul = lambda : map(int, input().strip().split())
mulf = lambda : map(float, input().strip().split())
seq = lambda : list(map(int, input().strip().split()))
ceil = lambda x: int(x) if x == int(x) else int(x) + 1
ceildiv = lambda x, d: x // d if x % d == 0 else x // d + 1
flush = lambda : stdout.flush()
stdstr = lambda : stdin.readline()
stdint = lambda : int(stdin.readline())
stdpr = lambda x: stdout.write(str(x))
mod = 1000000007

def solve(s, t):
	_dict = {'a': 0, 'b': 0, 'c': 0}
	pattern = 'abc'
	for word in s:
		if word not in _dict:
			_dict[word] = 1
		else:
			_dict[word] += 1
	if t == pattern:
		pattern = 'acb'
	if _dict['a'] == 0:
		pattern = 'bca'
	res = _dict[pattern[0]] * pattern[0] + _dict[pattern[1]] * pattern[1] + _dict[pattern[2]] * pattern[2]
	for key in sorted(_dict):
		if key not in ['a', 'b', 'c']:
			res += key * _dict[key]
	return res
t = inp()
res = []
for i in range(t):
	s = input()
	t = input()
	res.append(solve(s, t))
for i in res:
	print(i)


from collections import Counter

def check(s, t):
	i = 0
	j = 0
	for i in range(len(s)):
		if s[i] == t[j]:
			j += 1
		if j == 3:
			return True
	return False

def main():
	s = input()
	t = input()
	s = ''.join(sorted(s))
	if not check(s, t):
		print(s)
	else:
		c = Counter(s)
		res = 'a' * c['a']
		res += t[-1] * c[t[-1]]
		for k in sorted(c.keys()):
			if k not in res:
				res += k * c[k]
		print(res)
t = int(input())
while t:
	main()
	t -= 1


import sys

def forbidden_sequence(s, t):
	s = sorted(s)
	if t != 'abc':
		return ''.join(s)
	if 'a' not in s or 'b' not in s or 'c' not in s:
		return ''.join(s)
	a_end = 0
	b_end = 0
	c_end = 0
	for i in range(len(s)):
		if s[i] == 'a':
			a_end = i
		elif s[i] == 'b':
			b_end = i
		elif s[i] == 'c':
			c_end = i
		else:
			break
	s = s[:a_end + 1] + s[b_end + 1:c_end + 1] + s[a_end + 1:b_end + 1] + s[c_end + 1:]
	return ''.join(s)
for _ in range(int(input())):
	s = input()
	t = input()
	sys.stdout.write(f'{forbidden_sequence(s, t)}\n')


import sys
import os.path
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
	sys.stderr = open('error.txt', 'w')
depth = 200001
mod = 1000000007
lim = mod * mod
sys.setrecursionlimit(depth)
linp = lambda : list(minp())
minp = lambda : map(int, input().split())
from math import inf, ceil, sqrt, log2, gcd
from collections import defaultdict, deque
dxy = [(1, 0), (-1, 0), (0, 1), (0, -1)]

def expo(a, b):
	if not b:
		return 1
	v = expo(a, b // 2)
	v = v * v % mod
	if b % 2:
		v = v * a % mod
	return v

def modinv(a, b):
	d = expo(b, mod - 2)
	v = a * d % mod
	return v

def checkPrime(n):
	if n < 4:
		return True
	if n % 2 == 0:
		return False
	for i in range(3, int(sqrt(n)) + 1, 2):
		if n % i == 0:
			return False
	return True

def highestPowerof2(x):
	x |= x >> 1
	x |= x >> 2
	x |= x >> 4
	x |= x >> 8
	x |= x >> 16
	return x ^ x >> 1
for _ in range(int(input())):
	(s, t) = (input(), input())
	d = [0 for _ in range(26)]
	for e in s:
		d[ord(e) - ord('a')] += 1
	r = ''
	r += 'a' * d[0]
	if t == 'abc' and 'a' in s and ('b' in s) and ('c' in s):
		r += 'c' * d[2]
		r += 'b' * d[1]
	else:
		r += 'b' * d[1]
		r += 'c' * d[2]
	for i in range(3, 26):
		r += chr(ord('a') + i) * d[i]
	print(r)


import sys
from collections import deque

def f(l, n, f):
	a = 0
	x = n - 1
	while a <= x:
		m = a + (x - a) // 2
		if l[m] == f:
			return m
		elif l[m] > f:
			x = m - 1
		else:
			a = m + 1
	return None
for _ in range(int(sys.stdin.readline())):
	l = list(input())
	l2 = input()
	l.sort()
	if l2 == 'abc':
		d = {'a': 0, 'b': 0, 'c': 0}
		for i in range(len(l)):
			if l[i] in d:
				d[l[i]] += 1
			else:
				d.update({l[i]: 1})
		if d['a'] == 0 or d['c'] == 0:
			print(''.join(l))
		else:
			print(''.join(l[:d['a']] + l[d['a'] + d['b']:d['c'] + d['b'] + d['a']] + l[d['a']:d['a'] + d['b']] + l[d['c'] + d['b'] + d['a']:]))
	else:
		print(''.join(l))


t = int(input())
for _ in range(t):
	dic = {}
	s = input()
	for c in s:
		dic[c] = dic.get(c, 0) + 1
	t = input()
	if t == 'abc' and 'a' in dic and ('b' in dic) and ('c' in dic):
		for c in 'acbdefghijklmnopqrstuvwxyz':
			if c in dic:
				print(c * dic[c], end='')
	else:
		for c in 'abcdefghijklmnopqrstuvwxyz':
			if c in dic:
				print(c * dic[c], end='')
	print()


import sys
input = sys.stdin.readline
print = sys.stdout.write
for i in range(int(input())):
	a = list(input().strip())
	b = input().strip()
	a.sort(key=lambda k: ord(k))
	if b == 'abc' and 'a' in a and ('b' in a) and ('c' in a):
		a.sort(key=lambda k: ord('b') if k == 'c' else ord('c') if k == 'b' else ord(k))
	print(''.join(a) + '\n')


num_seqs = int(input())
for i in range(num_seqs):
	seq_sorted = ''.join(sorted(input()))
	verify = input()
	start = 0
	end = 0
	index_verify = 0
	changer = False
	result = ''
	parcial = ''
	if verify == 'abc':
		for i in range(len(seq_sorted)):
			if seq_sorted[i] == seq_sorted[end]:
				end = i
			else:
				if index_verify + 1 < len(verify) and seq_sorted[i] == verify[index_verify + 1]:
					index_verify += 1
				if changer and seq_sorted[i] == verify[index_verify]:
					parcial = seq_sorted[start:end + 1]
				else:
					result += seq_sorted[start:end + 1]
					if parcial:
						result += parcial
						parcial = ''
				changer = seq_sorted[end + 1] == verify[index_verify]
				start = i
				end = i
		result += seq_sorted[start:end + 1] + parcial
	else:
		result = seq_sorted
	print(result)


t = int(input())
for _ in range(t):
	s = sorted(input())
	t = input()
	s = ''.join(s)
	if 'a' in s and 'b' in s and ('c' in s) and (t == 'abc'):
		sx = s.count('a') + s.count('b') + s.count('c')
		print('a' * s.count('a') + 'c' * s.count('c') + 'b' * s.count('b') + s[sx:])
	else:
		print(s)


def main():
	T = int(input())
	while T > 0:
		T -= 1
		s = list(input())
		t = input()
		s.sort()
		a = 0
		b = 0
		c = 0
		for i in s:
			if i == 'a':
				a += 1
			elif i == 'b':
				b += 1
			elif i == 'c':
				c += 1
			else:
				break
		idx = a
		if t == 'abc' and a != 0:
			while True:
				if c != 0:
					s[idx] = 'c'
					c -= 1
					idx += 1
				elif b != 0:
					s[idx] = 'b'
					b -= 1
					idx += 1
				else:
					break
		elif t == 'acb' and a != 0:
			while True:
				if b != 0:
					s[idx] = 'b'
					b -= 1
					idx += 1
				elif c != 0:
					s[idx] = 'c'
					c -= 1
					idx += 1
				else:
					break
		print(''.join(s))
main()


import random
from collections import Counter, defaultdict
from copy import deepcopy as dc
import math
try:
	t = int(input())
	for tt in range(1, t + 1):
		a = list(input())
		b = list(input())
		d = sorted(a)
		c = list(set(a))
		c.sort()
		(x, y) = (''.join(map(str, b)), ''.join(map(str, c)))
		if not x in y and x != y:
			print(''.join(map(str, d)))
		else:
			i = d.index(b[-1])
			j = d.index(b[-2])
			x = sorted(a, reverse=True)
			k = x.index(b[-1])
			k = len(d) - k
			d = d[:j] + d[i:k] + d[j:i] + d[k:]
			print(''.join(map(str, d)))
except EOFError as e:
	pass


t = int(input())
for _ in range(t):
	text = input()
	permutation = input()
	text = sorted(text)
	text = ''.join(text)
	a = text.count('a')
	b = text.count('b')
	c = text.count('c')
	if permutation == 'abc' and a != 0 and (b != 0) and (c != 0):
		temp = 'a' * a + 'c' * c + 'b' * b
	else:
		temp = 'a' * a + 'b' * b + 'c' * c
	s = temp + text[a + b + c:]
	print(s)


import sys
tokens = ''.join(sys.stdin.readlines()).split()[::-1]

def next():
	return tokens.pop()

def nextInt():
	return int(next())

def nextFloat():
	return float(next())

def getIntArray(n):
	return [nextInt() for _ in range(n)]

def getFloatArray(n):
	return [nextFloat() for _ in range(n)]

def getStringArray(n):
	return [next() for _ in range(n)]
testcase = True

def solve(testcase=1):
	(S, T) = (next(), next())
	S = ''.join(sorted(list(S)))
	(a, b, c) = (S.count('a'), S.count('b'), S.count('c'))
	if T == 'abc' and a and b and c:
		ans = 'a' * a + 'c' * c + 'b' * b
		for i in range(len(S)):
			if S[i] not in T:
				ans += S[i:]
				break
		print(ans)
	else:
		print(''.join(S))
	pass
if testcase is None:
	testcaseCount = 1
	while tokens:
		solve(testcaseCount)
		testcaseCount += 1
else:
	testcaseCount = nextInt() if testcase else 1
	for tc in range(testcaseCount):
		solve(tc + 1)
	assert not tokens


from collections import defaultdict
for _ in range(int(input())):
	n1 = input()
	n2 = input()
	dp = defaultdict(int)
	for i in range(1, 27):
		dp[i] = 0
	for i in n1:
		x = ord(i) - 96
		dp[x] += 1
	ans = ''
	if 'abc' == n2:
		if dp[1] == 0:
			ans += 'b' * dp[2] + 'c' * dp[3]
		else:
			ans += 'a' * dp[1] + 'c' * dp[3] + 'b' * dp[2]
	else:
		ans += 'a' * dp[1] + 'b' * dp[2] + 'c' * dp[3]
	for i in range(4, 27):
		ans += chr(i + 96) * dp[i]
	print(ans)


T = int(input().rstrip())

def solve(s1, s2):
	cand = ''.join(sorted(set(s1)))
	idx = cand.find(s2)
	if idx == -1:
		return ''.join(sorted(s1))
	idx += 2
	candl = list(cand)
	(candl[idx - 1], candl[idx]) = (candl[idx], candl[idx - 1])
	d = {}
	for c in s1:
		if c not in d:
			d[c] = 1
		else:
			d[c] += 1
	news = ''
	for c in candl:
		count = d[c]
		rep_str = c * count
		news += rep_str
	return news
for test in range(T):
	s1 = input().rstrip()
	s2 = input().rstrip()
	res = solve(s1, s2)
	print(res)


def solve():
	(s, t) = (input(), input())
	s = ''.join(sorted(s))
	if t == 'abc' and 'a' in s and ('b' in s) and ('c' in s):
		s = s.count('a') * 'a' + 'c' * s.count('c') + 'b' * s.count('b') + s[s.rfind('c') + 1:]
	return s
for _ in range(int(input())):
	print(solve())


n = int(input())
for _ in range(n):
	text = input()
	per = input()
	text = sorted(text)
	text = ''.join(text)
	a = text.count('a')
	b = text.count('b')
	c = text.count('c')
	if per == 'abc' and a != 0 and (b != 0) and (c != 0):
		temp = 'a' * a + 'c' * c + 'b' * b
	else:
		temp = 'a' * a + 'b' * b + 'c' * c
	ans = temp + text[a + b + c:]
	print(ans)


import math
import functools
from sys import stdout
n = int(input())
for i in range(0, n):
	s = input()
	t = input()
	s = ''.join(list(sorted(s)))
	if t[1:] == 'bc' and 'a' in s and ('b' in s) and ('c' in s):
		a = s.count('a')
		c = s.count('c')
		b = s.count('b')
		s = s.replace('a', '')
		s = s.replace('b', '')
		s = s.replace('c', '')
		s = ''.ljust(a, 'a') + ''.ljust(c, 'c') + ''.ljust(b, 'b') + s
	print(s)


for _ in range(int(input())):
	givenstr = sorted(input())
	banned = input()
	res = ''
	count = 0
	for i in givenstr:
		if i == banned[count]:
			count += 1
		if count == 3:
			break
	if count == 3:
		cnt = givenstr.count(banned[-1])
		start = givenstr.index(banned[-1])
		res += ''.join(givenstr[:givenstr.index(banned[1])]) + ''.join(givenstr[start:start + cnt]) + ''.join(givenstr[givenstr.index(banned[1]):start]) + ''.join(givenstr[start + cnt:])
		print(res)
	else:
		print(*givenstr, sep='')


t = int(input())
for _ in range(t):
	s1 = input()
	s2 = input()
	if s2[1] + s2[2] != 'bc' or (not 'a' in s1 or not 'b' in s1 or (not 'c' in s1)):
		print(''.join(sorted(s1)))
	else:
		s1 = sorted(s1)
		l = s1.index('b')
		r = s1.index('c')
		s1 = s1[:l] + s1[r:r + s1.count('c')] + s1[l:r] + s1[r + s1.count('c'):]
		print(''.join(s1))


import re, collections
for _ in range(int(input())):
	s = list(input())
	r = input()
	s.sort()
	s = ''.join(s)
	x = 'abc' if r > 'abc' else 'acb'
	y = collections.Counter(x)
	for e in s:
		if e in y:
			y[e] += 1
	m = '123'
	if any((t == 1 for t in y.values())):
		print(s)
		continue
	for (i, k) in enumerate('abc'):
		s = s.replace(k * (y[k] - 1) + ':' * (y[k] - 1 == 0), m[i])
	l = 1
	for w in x:
		s = s.replace(str(l), w * (y[w] - 1))
		l += 1
	print(s)


for _ in range(int(input())):
	s = input()
	t = input()
	flag = 0
	l = [0] * 26
	for c in s:
		l[ord(c) - 97] += 1
	if l[1] > 0 and t == 'abc' and (l[2] > 0) and (l[0] > 0):
		flag = 1
	print('a' * l[0], end='')
	if flag:
		print('c' * l[2], end='')
		l[2] = 0
	for i in range(1, 26):
		print(chr(i + 97) * l[i], end='')
	print()


t = int(input())
for i in range(t):
	str = ''
	res = ''
	check = 0
	count = 0
	count1 = 0
	count2 = 0
	count3 = 0
	str1 = input()
	str2 = input()
	str1 = sorted(str1)
	str_len = len(str1)
	str = str.join(str1)
	b_and_c = {'a': '', 'b': '', 'c': ''}
	if str2 != 'abc' or str_len < 3:
		print(str)
		check = 1
	else:
		for j in range(str_len):
			if str[j] == 'a':
				b_and_c['a'] = b_and_c['a'] + 'a'
				count1 = count1 + 1
			elif str[j] == 'b':
				b_and_c['b'] = b_and_c['b'] + 'b'
				count2 = count2 + 1
			elif str[j] == 'c':
				b_and_c['c'] = b_and_c['c'] + 'c'
				count3 = count3 + 1
	if check == 0:
		if count1 != 0 and count2 != 0 and (count3 != 0):
			for j in range(count1):
				res = res + 'a'
			for j in range(count3):
				res = res + 'c'
			for j in range(count2):
				res = res + 'b'
			count = count1 + count2 + count3
			for j in range(count, str_len):
				res = res + str[j]
			print(res)
		else:
			print(str)


from collections import Counter
for _ in range(int(input())):
	s = input()
	t = input()
	c = sorted(Counter(s).items())
	if len(c) < 3 or c[0][0] != 'a' or c[1][0] != 'b' or (c[2][0] != 'c'):
		print(''.join([i * j for (i, j) in c]))
		continue
	if t == 'abc':
		d = [c[0], c[2], c[1]] + c[3:] if len(c) > 3 else [c[0], c[2], c[1]]
		print(''.join([i * j for (i, j) in d]))
	else:
		print(''.join([i * j for (i, j) in c]))


for _ in range(int(input())):
	(s, t) = (input(), input())
	s = ''.join(sorted(s))
	if t == 'abc' and 'a' in s and ('b' in s) and ('c' in s):
		s = s[:s.find('b')] + 'c' * s.count('c') + 'b' * s.count('b') + s[s.rfind('c') + 1:]
	print(s)


for _ in range(int(input())):
	s = list(map(str, input().split()))
	t = input()
	s[0] = sorted(s[0])
	if t != 'abc':
		print(*s[0], sep='')
	elif 'c' in s[0] and 'a' in s[0] and ('b' in s[0]):
		k = s[0].index('c')
		l = k
		while k < len(s[0]) and s[0][k] == 'c':
			k += 1
		f = s[0].index('b')
		m = s[0][:f] + s[0][l:k] + s[0][f:l] + s[0][k:]
		print(*m, sep='')
	else:
		print(*s[0], sep='')


def solve():
	str_ = input()
	abc = input()
	str_ = ''.join(sorted(str_))
	a = str_.find(abc[1])
	if a == -1:
		print(str_)
		return 0
	b = str_.find(abc[2])
	if b == -1:
		print(str_)
		return 0
	c = str_.find(abc[0])
	if c == -1:
		print(str_)
		return 0
	if abc != 'abc':
		print(str_)
		return 0
	index = len(str_)
	for i in range(b, len(str_)):
		if str_[i] != abc[2]:
			index = i - 1
			break
	str_ = str_[0:a] + str_[b:index + 1] + str_[a:b] + str_[index + 1:]
	print(str_)
	return 0
for t in range(int(input())):
	solve()


import os
import sys
from io import BytesIO, IOBase
import math
from decimal import Decimal
from decimal import *
from collections import defaultdict, deque
import heapq
import bisect
from decimal import Decimal
getcontext().prec = 25
abcd = 'abcdefghijklmnopqrstuvwxyz'
ABCD = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
months = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
MOD = 1000000007
BUFSIZE = 8192
from bisect import bisect_left, bisect_right

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	s = list(input())
	s = sorted(s)
	t = input()
	s = ''.join(sorted(s))
	if t == 'abc' and 'a' in s and ('b' in s) and ('c' in s):
		s = s[:s.find('b')] + s[s.find('c'):s.rfind('c') + 1] + s[s.find('b'):s.find('c')] + s[s.rfind('c') + 1:]
	print(s)


for _ in range(int(input())):
	s = input()
	t = input()
	if t == 'abc':
		u = list(sorted(s))
		if 'a' in u and 'b' in u and ('c' in u):
			ib = u.index('b')
			ic = u.index('c')
			ric = len(u) - u[::-1].index('c')
			u = u[:ib] + u[ic:ric] + u[ib:ic] + u[ric:]
		print(''.join(u))
	else:
		print(''.join(sorted(s)))


for i in range(int(input())):
	s = input()
	t = input()
	z = [0] * 26
	for i in s:
		z[ord(i) - ord('a')] += 1
	if t == 'abc' and z[0] and z[1] and z[2]:
		print('a' * z[0] + 'c' * z[2] + 'b' * z[1], end='')
		for i in range(3, 26):
			print('abcdefghijklmnopqrstuvwxyz'[i] * z[i], end='')
		print()
	else:
		for i in range(26):
			print('abcdefghijklmnopqrstuvwxyz'[i] * z[i], end='')
		print()


t = int(input())
for i in range(t):
	a = str(input())
	b = str(input())
	if ('a' or 'b' or 'c') not in a:
		print(''.join(sorted(a)))
	elif b == 'abc':
		(noa, nob, noc) = (0, 0, 0)
		final = ''.join(sorted(a))
		for j in final:
			if j == 'a':
				noa += 1
			elif j == 'b':
				nob += 1
			elif j == 'c':
				noc += 1
		print('a' * noa + 'c' * noc + 'b' * nob + final[noa + nob + noc:])
	else:
		print(''.join(sorted(a)))


T = int(input())
while T > 0:
	T -= 1
	str1 = input().strip()
	cnt = [0] * 26
	for c in str1:
		cnt[ord(c) - 97] += 1
	str2 = input().strip()
	str2 = 'acb' if str2 == 'abc' and all([cnt[idx] for idx in range(3)]) else 'abc'
	for alp in str2:
		while cnt[ord(alp) - 97] > 0:
			cnt[ord(alp) - 97] -= 1
			print(alp, end='')
	for idx in range(26):
		while cnt[idx] > 0:
			cnt[idx] -= 1
			print(chr(97 + idx), end='')
	print('')


t = int(input())
for i in range(t):
	S = list(input())
	T = input()
	a = S.count('a')
	b = S.count('b')
	c = S.count('c')
	if T == 'abc' and a > 0 and (b > 0) and (c > 0):
		result = 'a' * a + 'c' * c + 'b' * b
	else:
		result = 'a' * a + 'b' * b + 'c' * c
	S.sort()
	for i in S:
		if i not in T:
			result += i
	print(result)


import sys
input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())
from collections import Counter
t = inp()
for _ in range(t):
	s = input()
	t = input().strip()
	if t != 'abc':
		print(''.join(sorted(list(s))))
	else:
		ct = Counter(s)
		if ct['a'] == 0 or ct['b'] == 0 or ct['c'] == 0:
			print(''.join(sorted(list(s))))
		else:
			res = 'a' * ct['a'] + 'c' * ct['c'] + 'b' * ct['b']
			for i in range(ord('d'), ord('z') + 1):
				res += chr(i) * ct[chr(i)]
			print(res)


import itertools
import sys
input = lambda : sys.stdin.readline().rstrip()

def main():
	T = int(input())
	for _ in range(T):
		s = input()
		t = input()
		x = list(sorted(s))
		if t[0] not in x or t[1] not in x or t[2] not in x or (t[0] == 'b') or (t[0] == 'c'):
			print(''.join(x))
		else:
			nove = ''
			prve = ''
			druhe = ''
			stare = ''
			i = 0
			while i != len(x) and x[i] != t[1]:
				nove += x[i]
				i += 1
			while i != len(x) and x[i] != t[2]:
				prve += x[i]
				i += 1
			while i != len(x) and x[i] == t[2]:
				druhe += x[i]
				i += 1
			while i != len(x):
				stare += x[i]
				i += 1
			cele = nove + druhe + prve + stare
			print(''.join(cele))
main()


from collections import Counter
T = int(input())
for _ in range(T):
	S = input().strip()
	T = input().strip()
	cnt = Counter(S)
	if cnt['a'] == 0 or cnt['b'] == 0 or cnt['c'] == 0:
		print(''.join(sorted(S)))
	elif T == 'abc':
		ans = ''
		ans += 'a' * cnt['a']
		ans += 'c' * cnt['c']
		ans += 'b' * cnt['b']
		for i in 'defghijklmnopqrstuvwxyz':
			ans += i * cnt[i]
		print(''.join(ans))
	else:
		print(''.join(sorted(S)))


import sys
input = sys.stdin.readline

def solve():
	(s, t) = (input(), input())
	s = s[:len(s) - 1]
	t = t[:len(t) - 1]
	s = ''.join(sorted(s))
	if t == 'abc' and 'a' in s and ('b' in s) and ('c' in s):
		s = s.count('a') * 'a' + 'c' * s.count('c') + 'b' * s.count('b') + s[s.rfind('c') + 1:]
	return s
for _ in range(int(input())):
	print(solve())


for _ in range(int(input())):
	s = ''.join(sorted(input()))
	t = input()
	if t == 'abc' and all((x in s for x in 'abc')):
		tem = s.count('c')
		s = s.replace('c', 'b')
		print(s.replace('b', 'c', tem))
	else:
		print(s)


from sys import stdin
from collections import Counter
input = stdin.readline
rn = lambda : int(input())
rns = lambda : map(int, input().split())
rl = lambda : list(map(int, input().split()))
rs = lambda : input().strip()
YN = lambda x: print('YES') if x else print('NO')
ceil_div = lambda a, b: -(-a // b)
mod = 10 ** 9 + 7
for _ in range(rn()):
	s = rs()
	t = rs()
	c = Counter(s)
	ans = ''
	if 'a' in c and 'b' in c and ('c' in c):
		if t == 'abc':
			t = 'acb'
		else:
			t = 'abc'
		for ch in t:
			ans += c[ch] * ch
			del c[ch]
	for ch in sorted(c.keys()):
		ans += c[ch] * ch
	print(ans)