In optical bands, the spectra of M giants often overlap with those of M dwarfs due to their similarities, especially for low or moderate resolution spectra. Traditionally, several feature indices, such as Na i, CaH, TiO5, and K i, are used to distinguish between M giants and M dwarfs. However, these features are selected by experience based on a small amount of standard spectra. Hence, it is not clear if these features are the most effective ones to detect M giants. In this paper, we use a machine-learning method, eXtreme Gradient Boosting (XGBoost), to discern M giants from M dwarfs for spectroscopic surveys. The important feature bands for distinguishing between M giants and M dwarfs are accurately identified by the XGBoost method through evaluating and quantifying the importance of each feature in spectra, including Na i, B1, and Ca ii, which are consistent with previous studies. Moreover, we find that a blend feature around 6564 Å (named B2) is sensitive to luminosity and that the feature combinations of both B1 versus CaH and B2 versus CaH, based on the average spectral flux, are important in distinguishing M giants from M dwarfs. Furthermore, our XGBoost prediction model achieves 99.79% overall accuracy and 96.87% recognition precision for M giants, outperforming the other three popular machine-learning algorithms (i.e., SVM, random forests, and ELM). Using such a prediction model, we detected 28,714 M-giant spectra from LAMOST DR5 and thus provided a larger amount of M giants for related scientific research.