Java 为什么在这种情况下不能使用子字符串?
我在试着把句子中的单词分开。句子中的每个单词都存储在字符串Java 为什么在这种情况下不能使用子字符串?,java,string,api,substring,Java,String,Api,Substring,我在试着把句子中的单词分开。句子中的每个单词都存储在字符串word,然后再将所有内容添加回一个字符串中 但是为什么子字符串行会出错呢 String sent = IO.readString(); char x; String word =""; int count = 0; for(int i = 0; i < sent.length(); i++){ x = sent.charAt(i);
word
,然后再将所有内容添加回一个字符串中
但是为什么子字符串行会出错呢
String sent = IO.readString();
char x;
String word ="";
int count = 0;
for(int i = 0; i < sent.length(); i++){
x = sent.charAt(i);
if(x == ' ')
{
word = sent.substring(x-count,x);
word = word + ' ';
count =0;
}
count++;
}
String sent=IO.readString();
字符x;
字串=”;
整数计数=0;
for(int i=0;i
word=sent.substring(x-count,x)代码>应该是word=sent.substring(i-count,i)
word=sent.substring(x-count,x)代码>应该是word=sent.substring(i-count,i)因为这里的x
是char
,而不是int
word = sent.substring(x-count,x);
它应该(可能)是这样的
word = sent.substring(i-count,i);
因为i
是字符串中的位置
,因为x
在这里是字符
,而不是int
word = sent.substring(x-count,x);
它应该(可能)是这样的
word = sent.substring(i-count,i);
因为<代码> i <代码>是<代码>字符串中的位置。您应该考虑使用<代码> String .Struts.()/代码>,它返回<代码>字符串Stray.< /P>
文件:
要使用空格和标点符号作为分隔符,可以执行以下操作:
String[] arrWords = sentence.split("([ ,.]+)");
如果你真的想继续你原来的路线,你必须为第一个单词和最后一个单词添加一些特殊的情况。但是,当有多个空格或标点符号时会发生什么?测试它并找出答案
public class SeparateWords
{
public static void main(String[] args)
{
String sent ="Hello there how are you";
char x;
String word ="";
int count = 0;
for(int i = 0; i <= sent.length(); i++){
if (i == sent.length()){
word = sent.substring(i-count+1,i);
System.out.println(word);
break;
}
x = sent.charAt(i);
if(x == ' ')
{
if ((i-count) == 0){
word = sent.substring(i-count,i);
}
else{
word = sent.substring(i-count+1,i);
}
System.out.println(word);
word = word + ' ';
count =0;
}
count++;
}
}
}
您应该考虑使用<代码> String .SPLIT()/Cyto>,它返回<代码>字符串< /Cord>数组.< /P>
文件:
要使用空格和标点符号作为分隔符,可以执行以下操作:
String[] arrWords = sentence.split("([ ,.]+)");
如果你真的想继续你原来的路线,你必须为第一个单词和最后一个单词添加一些特殊的情况。但是,当有多个空格或标点符号时会发生什么?测试它并找出答案
public class SeparateWords
{
public static void main(String[] args)
{
String sent ="Hello there how are you";
char x;
String word ="";
int count = 0;
for(int i = 0; i <= sent.length(); i++){
if (i == sent.length()){
word = sent.substring(i-count+1,i);
System.out.println(word);
break;
}
x = sent.charAt(i);
if(x == ' ')
{
if ((i-count) == 0){
word = sent.substring(i-count,i);
}
else{
word = sent.substring(i-count+1,i);
}
System.out.println(word);
word = word + ' ';
count =0;
}
count++;
}
}
}
这是一个秘密错误吗?或者你可以和我们分享,这样我们可以帮助你?错误消息通常包含有用的信息——不要对我们隐瞒。您收到的错误是什么,输入的是什么(即发送的值是多少?
)?你希望看到什么?你给我们的越多,我们就越容易回答。事实上,你给我们的越多,你就越有可能自己找到解决方案(这是一项非常有用的技能),这是一个秘密错误吗?或者你可以和我们分享,这样我们可以帮助你?错误消息通常包含有用的信息——不要对我们隐瞒。您收到的错误是什么,输入的是什么(即发送的值是多少?
)?你希望看到什么?你给我们的越多,我们就越容易回答。事实上,您给我们的越多,您就越有可能自己找到解决方案(这是一项非常有用的构建技能)。这是一个很好的例子,说明了为什么您不应该走这条路,而应该使用现有的、经过良好测试的实用程序类,比如感谢String.split()技巧!感谢您对rest.True的解释,这是一个示例,说明了为什么您不应该走这条路,而应该使用现有的、经过良好测试的实用程序类,比如感谢String.split()技巧!谢谢你解释其余的。谢谢你解释!谢谢你的解释!