熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java:逆轉字符串

2013-11-23 19:27:30  來源: Java核心技術 

  package comturdemo;

  public class Hello {

  public static void main(String[] args) {

  Systemoutprintln(reverseWords(How are you!));

  Systemoutprintln(reverseWords(do justice to a dinner));

  Systemoutprintln(reverseWords());

  Systemoutprintln(reverseWords(A));

  Systemoutprintln(reverseWords(A Biao));

  Systemoutprintln(reverseWords(!A Biao C));

  }

  public static String reverseWords(String str) {

  int start = ;

  int end = ;

  char[] chs = strtoCharArray();

  // 先逆轉整個字符串

  reverseCharactersInRange(chs chslength );

  // 再逆轉逆轉後的字符數組中組成單詞的字符

  for (int i = ; i < chslength; ++i) {

  if (CharacterisLetter(chs[i])) {

  // 找到組成單詞的字符的起始和結束位置

  if (start > end) {

  start = end = i;

  } else {

  ++end;

  }

  } else {

  if (start < end) {

  reverseCharactersInRange(chs start end);

  }

  start = chslength;

  }

  }

  if (start < end) {

  reverseCharactersInRange(chs start end);

  }

  return new String(chs);

  }

  public static void reverseCharactersInRange(char[] chs int start int end) {

  int times = (end start + ) / ;

  for (int i = ; i < times; ++i) {

  char temp = chs[start + i];

  chs[start + i] = chs[end i];

  chs[end i] = temp;

  }

  }

  }


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26906.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.