计数重复字符数 [英] Count number of repeated character
问题描述
String str ="1-300,1-300,1-300,1-200,1-200";
我的输出是
我必须数1-300是3倍1-200是2时
String str="1-300,1-300,1-300,1-200,1-200";
MY output is
i have to count 1-300 is 3 times 1-200 is 2 time
推荐答案
好,这是一项家庭作业.
我会给您建议,但没有代码-至少没有完整的代码.
那该怎么办?
首先,您需要拆分字符串.可以使用 StringTokenizer [ ^ ]:
Ok, this is a homework task.
I will give you advice, but no code - at least no complete.
So what to do?
First of all you need to split the String. This can be done by using StringTokenizer[^]:
String strValue="1-300,1-300,1-300,1-200,1-200";
StringTokenizer oTokenizer = new StringTokenizer(strValue, ",");
然后,您可以使用oTokenizer.next()
遍历StringTokenizer,它返回下一个值. 记住:循环.那是for
或while
循环.
其他版本:
可以使用字符串自己的方法 ^ ].该代码返回一个String Array,您也可以循环遍历.
拆分完成后,您只需要将每个位与其他位进行比较即可.那是一个循环.我会让你弄清楚,我想这就是这项作业的主意.
我强烈建议阅读String对象的文档(请参阅上面的链接),因为那是您将不得不经常处理的文档.
玩得开心,如果有其他问题或需要进一步的解释,请询问.
You can then loop through the StringTokenizer by using oTokenizer.next()
, which returns the next value. Remember: loop. That''s a for
or while
loop.
Other version:
The String can be split by the String''s own method String.split(String strDelimiter)[^]. That one returns a String Array, which you can also loop through.
After the splitting is done you''ll just have to compare each bit with the others. That''s a loop in a loop. I''ll let you figure that out, I guess that''s the idea of this homework.
I strongly suggest to read the documentation for the String Object (see link above), cause that''s one you will have to deal with very often.
Have fun and please ask when you have additional questions or need further explanation.
看看indexOf()方法. com/javase/1.5.0/docs/api/java/lang/String.html> String
[
Take a look at theindexOf()
method of theString
[^] class.
使用完美答案完美工作
公共类CountYourRepeatedValue {
public static int countNo(String subStr,String str){
返回(str.length()-str.replace(subStr,").length())/subStr.length();
}
公共静态void main(String [] args){
System.out.println(countNo("1-300","1-300,1-300,1-300,1-200,1-200"));
}
}
来自,
Haresh Prajapati
Perfect Work with Perfect Answer
public class CountYourRepeatedValue{
public static int countNo(String subStr, String str){
return (str.length() - str.replace(subStr, "").length()) / subStr.length();
}
public static void main(String[] args){
System.out.println(countNo("1-300", "1-300,1-300,1-300,1-200,1-200"));
}
}
From,
Haresh Prajapati
这篇关于计数重复字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!