日期:2014-05-20 浏览次数:21247 次
String x ="_hjk2io_jie@n3hf4_"; //一个字符串。
x="@hjkiio@jie_nhhhf4"
String x = "_hjk2io_jie@n3hf4_";
if (x.charAt(x.length() - 1) == '_')
x = x.substring(0, x.length() - 1);
char[] temp = x.toCharArray();
StringBuffer y = new StringBuffer();
for (int i = 0; i < x.length(); i++) {
if (temp[i] == '_')
y.append('@');
else if (temp[i] == '@')
y.append('_');
else if (temp[i] >= '0' && temp[i] <= '9' && i < x.length() - 1
&& ('0' < temp[i + 1] || temp[i + 1] < '9'))
y.append(temp[i + 1]).append(temp[i + 1]);
else
y.append(temp[i]);
}
System.out.println(y);
------解决方案--------------------
public class Test
{
public static String change(String str)
{
StringBuilder strBuilder = new StringBuilder(str);
if (strBuilder.charAt(strBuilder.length() - 1) == '_')
{
strBuilder.setLength(strBuilder.length() - 1);
}
for (int i = 0; i < strBuilder.length(); i++)
{
if (strBuilder.charAt(i) == '_')
{
strBuilder.setCharAt(i, '@');
}
else if (strBuilder.charAt(i) == '@')
{
strBuilder.setCharAt(i, '_');
}
else if (Character.isDigit(strBuilder.charAt(i)) && i != strBuilder.length() - 1)
{
int t = Integer.parseInt(strBuilder.substring(i, i + 1));
strBuilder.deleteCharAt(i);
for (int j = 1; j < t; j++)
{
strBuilder.insert(i, strBuilder.charAt(i));
}
}
}
return strBuilder.toString();
}
public static void main(String[] args)
{
String str = "_hjk2io_jie@n3hf4_";
System.out.println(change(str));
}
}
------解决方案--------------------
修正一下,当然用上正则能清晰很多,但是我看见正则就头晕!
String x = "_hjk2io_jie@n3hf4_";
if (x.charAt(x.length() - 1) == '_')
x = x.substring(0, x.length() - 1);
char[] temp = x.toCharArray();
StringBuffer y = new StringBuffer();
for (int i = 0; i < x.length(); i++) {
if (temp[i] == '_')
y.append('@');
else if (temp[i] == '@')
y.append('_');
else if ((temp[i] >= '0' && temp[i] <= '9')
&& i < x.length() - 1
&& (('a' < temp[i + 1] || temp[i + 1] < 'z') && ('A' < temp[i + 1] || temp[i + 1] < 'Z')))
y.append(temp[i + 1]).append(temp[i + 1]);
else
y.append(temp[i]);
}
System.out.println(y);