java

位置:IT落伍者 >> java >> 浏览文章

Java:逆转字符串


发布日期:2020年02月14日
 
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;

}

}

}

               

上一篇:java内省机制

下一篇:JavaMail发送中文邮件中主题乱码的解决方法