写了一个小程序,但有个小错误,不知道怎么改??我是新手,求指教!
这是个字符串转换的小程序,要求一句字符串间多余空格变为一个,并且每个单词首字母大写。但是我写的程序中有一句话总显示错误,不知道怎么改,求指教?例如:
用户输入:
you and me what cpp2005program
则程序输出:
You And Me What Cpp2005program
import java.util.*;
public class trans {
public static void main(String[] args) {
Scanner str=new Scanner(System.in);
String p,q;
p=str.nextLine();
p=p.replaceAll(" +", " ");
char[] p1=p.toCharArray();
char[] q1=q.toCharArray();
int i;
for(i=0;i<p1.length;i++)
{if((p1.charAt(i)==' ')&&(p1[i+1]>='a')&&(p1[i+1]<='z')||(i=0))
{
q1[i+1]=(char) (p1[i+1]-32);
}
else q1[i]=p1[i];
}
System.out.println(q1);
}
}
----------------解决方案--------------------------------------------------------
Java我也是新手,还有好多方法还没有学。。。不懂帮顶了
----------------解决方案--------------------------------------------------------
程序代码:
public static void main(String[] args) {
Scanner str = new Scanner(System.in);
String p;
p = str.nextLine();
p = p.replaceAll(" +", " ");
String[] p1 = p.split(" ");
String s ="";
for(int i=0;i<p1.length;i++){
if(p1[i].charAt(0)>='a'&&p1[i].charAt(0)<='z'){
p1[i]=p1[i].substring(0, 1).toUpperCase()+p1[i].substring(1, p1[i].length());
}
s+=p1[i]+" ";
}
System.out.println(s);
}
Scanner str = new Scanner(System.in);
String p;
p = str.nextLine();
p = p.replaceAll(" +", " ");
String[] p1 = p.split(" ");
String s ="";
for(int i=0;i<p1.length;i++){
if(p1[i].charAt(0)>='a'&&p1[i].charAt(0)<='z'){
p1[i]=p1[i].substring(0, 1).toUpperCase()+p1[i].substring(1, p1[i].length());
}
s+=p1[i]+" ";
}
System.out.println(s);
}
----------------解决方案--------------------------------------------------------
这个我碰到过
比如 :you and me what cpp2005program是你想要转换的吧,但是你用char[] p1=p.toCharArray();这个的话它是把前面的话转成you and me what cpp2005program 这样五个元素的数组了,知道不?而不是你想要的每个字母的数组。希望对你有用,谢谢。
----------------解决方案--------------------------------------------------------
可以用正则
----------------解决方案--------------------------------------------------------
我自己也研究出来能够运行的程序了,不过还是很谢谢大家。我的程序是
import java.util.*;
public class trans {
public static void main(String[] args) {
Scanner str=new Scanner(System.in);
String p;
p=str.nextLine();
p=p.replaceAll(" +", " ");
char[] p1=p.toCharArray();
int i;
if (Character.isLowerCase(p1[0]))
p1[0]=Character.toUpperCase(p1[0]);
for(i=1;i<p1.length;i++)
{ if((p1[i]==' ')&&(p1[i+1]>='a')&&(p1[i+1]<='z'))
{p1[i+1]=(char)(p1[i+1]-32);}
}
System.out.println(p1);
}
}
----------------解决方案--------------------------------------------------------