我有一个字符串,比如 automatic 或 auter。而且我想确保如果字母“u”跟在字母“a”之后,字符会反转。
说
Input: automatic
Output: uatomatic
Input: auter
Output: uater
Input: auauauauauauau
Output:uuuuuuuaaaaaaa
是否可以一次性完成?
编辑:我有一个 C 实现,但我不确定如何就地反转字符串,这样我的整行就不会被反转,只是单词。
char* characterReverse(char* input) {
char temp;
int low = 0;
int length = strlen( input );
int high = length - 1;
while ( low <= high )
{
temp = input[ low ];
input[ low ] = input[ high ];
input[ high ] = temp;
low++;
high--;
}
return input;
这是一个适用于您的测试用例的 C# 实现(请注意,它仅适用于小写字母。如果您需要不区分大小写的版本,请告诉我):
static void Main(string[] args)
{
string input1 = "automatic";
string input2 = "auter";
string input3 = "auauauauauauau";
Console.WriteLine("Input: {0}{2}Output: {1}{2}", input1, ReverseAu(input1), Environment.NewLine);
Console.WriteLine("Input: {0}{2}Output: {1}{2}", input2, ReverseAu(input2), Environment.NewLine);
Console.WriteLine("Input: {0}{2}Output: {1}{2}", input3, ReverseAu(input3), Environment.NewLine);
}
private static string ReverseAu(string input)
{
char[] chars = input.ToCharArray();
int ndx = input.IndexOf("au", StringComparison.Ordinal);
while (ndx > -1)
{
chars[ndx] = 'u';
chars[ndx + 1] = 'a';
input = new string(chars);
chars = input.ToCharArray();
ndx = input.IndexOf("au", StringComparison.Ordinal);
}
return input;
}