翻转字符串
1. i am a student《=》tneduts a ma i 两边对称
void flipString(char*arr,int lowIndex,int len) { if(len<2){ return; } int highIndex = len-1;while (lowIndex < highIndex) { char tmp = arr[highIndex];//数组内容进行翻转 arr[lowIndex] = arr[lowIndex]; arr[right] = tmp; highIndex--; lowIndex++; } }
2. i am a student =>student a am i
第一步直接调用flipString,实现 i am a student =》tneduts a ma i=》student a am i
第二步实现单词的翻转。
reverseWord(char* arr, int len){ int index = 0 int wordLen = 0; flipString(arr,0,len); while(arr[index] !='\0'){ if(arr[index]==' '){
int indexStart = index-wordLen; flipString(&arr[indexStart],indexStart,wordLen); wordLen = 0; }else{ wordLen++; } index++; } }