java中给定一个字符串,反转其中的元音字母

package com.text.lianxi;

import java.util.Scanner;

public class Text {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s = "leetcode";
		Text sv = new Text();
		String res = sv.reverseVowels(s);
		System.out.println(res);
	}

	public String reverseVowels(String s) {
		// 将字符串中的原因反转存储
		String reverString = new StringBuffer(s).reverse().toString();
		// 存储反转后的元音
		String vols = "";
		int sl = s.length();
		for (int i = 0; i < s.length(); i++) {
			char c = reverString.charAt(i);
			if (c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c == 'I' || c == 'o' || c == 'O' || c == 'u'
					|| c == 'U') {
				vols = vols + c;
			}
		}

		// 然后在按原顺序在字符串中查找元音 找到后就替换
		String res = "";
		int t = 0;// 检索vols中的元音
		for (int i = 0; i < sl; i++) {
			char c = s.charAt(i);
			if (c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c == 'I' || c == 'o' || c == 'O' || c == 'u'
					|| c == 'U') {
				res += vols.charAt(t);
				t++;
			} else// 若不是元音则按原顺序
			{
				res += c;
			}
		}
		return res;
		// toCharArray():将字符串转换成字符数组,便于对每一个字符进行单独操作
	}
}

你可能感兴趣的:(面试手写题)