将最大的字符移到前面

时间:2018-09-15 15:53:35

标签: c string loops

该代码接受字符串str作为参数,从字符串中找到最大的字符,然后将其移至字符串的开头。

class ThreadDemo implements Runnable {
    private String threadName;

    ThreadDemo(String name) {
        this.threadName = name;
    }

    @Override
    public void run() {
        System.out.println("Thread " + threadName + " exiting.");
    }

}
public class Problem2 {
    public static void main(String[] args) {
        ThreadDemo runnable1 = new ThreadDemo("Thread-1");
        ThreadDemo runnable2 = new ThreadDemo("Thread-2");

        Thread t1 = new Thread(runnable1);
        Thread t2 = new Thread(runnable2);

        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            System.out.println("ERROR!");
        }
        System.out.println("completed");
    }
}

代码

Example 1 (Single instance of large char)
Input: adebc
Output:eadbc

Example 2 (Multiple instance of large char)
Input: agfcdeg 
Output:gafcdeg

但是,我的代码没有将最大的char移到它的前面,而剩下的保留了,所以我的代码只是用代码替换了第一个字符。

void maxCharToFront(char *str) { int large, i = 0; char first; large = str[i]; /* Find largest character */ while (str[i] != '\0') { if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) { if (str[i] > large) { large = str[i]; } } i++; } for(int i = 0; i < strlen(str); i++) str[i] = str[i+1]; /*Move largest character to the front*/ first = str[0]; str[0]=large; str[1] = first; }

我该如何改善?

1 个答案:

答案 0 :(得分:0)

请考虑以下建议:

  1. 您只需要存储最大字符的位置。
  2. 第二个for循环并不需要一直循环到字符串末尾。
  3. 您不需要交换第一个字符和最大字符,因为您已经调整了字符串,因此可以将最大字符直接存储在第0个位置。

示例代码

void maxCharToFront(char *str)
{
 int  i = 0;
 int pos=0;

 /* Find largest character */
 while (str[i] != '\0')
 {
    if ((str[i] >= 'a' && str[i] <= 'z') ||
        (str[i] >= 'A' && str[i] <= 'Z'))
        {
            if (str[i] > str[pos])
            {

                pos = i;
            }
        }
        i++;
 }

 char large = str[pos];

 for(int i = pos; i > 0; i--)
    str[i] = str[i-1];

  str[0] = large;

}