題目
實現串str的逆轉函數,如果str爲空串,則什麼都不做。
分析
由於串str是一個字符數組,所以逆轉字符串,即逆轉數組中的元素。
其實是個逆置問題。
代碼
C語言代碼
void swap(char &c1,char &c2) {
char temp=c1;
c1=c2;
c2=temp;
}
void invert(Str &str) {
int i=0,j=str.length-1;
while(i<j) {
swap(str.ch[i],str.ch[j]);
i++;
j--;
}
}
Java代碼
public class Demo1 {
public static void main(String[] args) {
String str="ABCDEFG";
char[] chars = str.toCharArray();
int i=0,j=chars.length-1;
while (i<j){
char temp=chars[i];
chars[i]=chars[j];
chars[j]=temp;
i++;
j--;
}
for (char aChar : chars) {
System.out.print(aChar);
}
}
}