c - 重新排列字符串,使字母 'x' 后面永远不会跟字母 'y'

标签 c algorithm

<分区>

我有一个字符串,比如 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;
    }

关于c - 重新排列字符串,使字母 'x' 后面永远不会跟字母 'y',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23795589/

相关文章:

c - 没有 return 语句的函数的返回值是多少?

c - 识别 C 客户端/服务器程序中不同类型的客户端

algorithm - 如何从 map 转换MapResult!到整数数组?

algorithm - 链表循环检测

c - stm32f103中多 channel 转换中adc的转换顺序

c - 如何在多线程中使用 printf()

c++ - 将 C++ 类转换为 C 结构(以及更多)

algorithm - 这种重复可以有多少个子问题,同时仍然比初始重复更快?

c# - 如何从数组中找到前几个值?

html - 如何输出没有 "widows"的多列 html?