作者adrianshum (Alien)
看板java
标题Re: [问题] 如何把Strings里面分成很多不同的东西
时间Fri Feb 5 16:51:03 2010
※ 引述《BlackMatrix (BlackMatrix)》之铭言:
: 问题是, 我想把一个一串Strings加数字让他变得不一样
: 有四种条件:
: The return value will be the ROT13 encoding of the input file. For our
: purposes the ROT13 algorithm is defined as follows:
: A) If the input is a lower case letter, the output is the lower case
: letter plus 13 (with wrap-around, so 'n' becomes 'a')
: B) If the input is a upper case letter, the output is the upper case
: letter plus 13 (with wrap-around, so 'n' becomes 'a')
: C) If the input is a number the output is the number plus 5 (with
: wrap-around so '6' becomes '1')
: D) If the input is neither letter nor number, the output is the same
: as the input ('!' becomes '!' and ' ' becomes ' ')
: 也就是说:
: 假如我的文件, test.txt里面的一串字是1234那就会变成5678, 然後
: 1a2a3a4a 就会变成 5n6n7n8n 因为a+13会变成n, 大写跟小写都会
: 我现在可以用Scanner跟Reader来读取我的strings, 可是重点是我不会改变他们的数字或
: 是字母
: 问题1:
: a+13会变成a13, 那要怎麽才能让他跳13个字母
: 111我+5会变成545454...非常诡异
: 问题2:
: 因为我之前有学过C++, 我就想说把Strings当成Array of Chars可是似乎没办法
: 所以我就把他全部都写到 char[] charArray = new char [encodedFile.length()]
: 然後利用.charAt(i) <== i 是用for loop
: 我现在所有的字母跟数字都在Array of Char里面, 可是我要怎麽用if statement来表示
: A. 如果碰到字母要跳13位
: B. 如果碰到数字要+5
: 目前我A完全不会做, B我这样写, charArray[5] += 5是没办法这样做的.
: 因为我似乎把Char当成Int来用, 所以...到底该怎麽办
: 我在网上查了很多资料, 我有用Replace可是完全没办法用
: 我的Code在底下:
: http://nopaste.csie.org/a4a9b
: 第一次写Java, 买了Just Java2 可是没有帮助我太多
: 因为实在写不出来, 请大家麻烦指点指点
给你一点提示
我下面写的东西.
是把一条 String, 里面的大草变小草, 小草变大草.
把里面用到的东西搞懂, 你的问题也就不难做了
public static String changeCase(String input) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c >= 'a' && c <= 'z') {
c = (char)(c - 32);
} else if (c >= 'A' && c <= 'Z') {
c = (char)(c + 32);
}
sb.append(c);
}
return sb.toString();
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 61.238.156.189
1F:推 BlackMatrix:我似乎有点弄明白一点怎麽做了, 谢谢!!~~~ 02/05 17:00
2F:推 BlackMatrix:我已经把Code做出来了,谢谢,原来字母&数字 => ASCII 02/05 17:46
3F:→ adrianshum:你要搞懂,char 其实也只是一个整数而已 02/06 00:19