CTCI---8.1.4

/**
 * 
 */
package Chapter_8;

import java.util.Scanner;

/**
 * @author MohnSnow
 * @time 2015年5月22日 上午9:57:30
 * 
 */
public class chapter8_1_4 {

	/**
	 * @param argsmengdx
	 *            -fnst
	 * @title 空格全部替换为%20,不建议使用字符串处理,使用字符数组去处理
	 */
	private static void spaceReplace(String str_a) {
		char[] temp = str_a.toCharArray();
		int space_count = 0;
		int new_count = temp.length;
		// System.out.println(temp[4]);一个字符占一个位置
		for (int i = 0; i < temp.length; i++) {
			if (temp[i] == ' ') {// 此处应该注意形式:if (temp[i] ==
									// " "),区分字符串和字符的空格的表现形式否则会提示Incompatible
									// operand types char and String
				space_count++;
			}
		}
		new_count += 2 * space_count;// 空格转换为%,另外还有两个字符0和2
		char[] result = new char[new_count];
		for (int i = 0, j = 0; i < temp.length && j < new_count; i++) {
			if (temp[i] == ' ') {
				result[j++] = '%';
				result[j++] = '2';
				result[j++] = '0';
			} else {
				result[j++] = temp[i];
			}
		}
		System.out.println(result);
	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		String a = in.nextLine();
		spaceReplace(a);
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值