static int countChars( String str, char searchChar ) {
// Count the number of times searchChar occurs in
// str and return the result.
int i; // A position in the string, str.
char ch; // A character in the string.
int count; // Number of times searchChar has been found in str.
count = 0;
for ( i = 0; i < str.length(); i++ ) {
ch = str.charAt(i); // Get the i-th character in str.
if ( ch == searchChar )
count++;
}
return count;
}
我试图打印出函数中的值来计算字符串中出现的字符数,但是我不确定如何从main函数中执行此操作。
答案 0 :(得分:0)
试试这个:
public static void main(String[] args) {
String mySearchString="Stringtosearch";
char ch='s';
System.out.println( countChars(mySearchString, ch) );
}
答案 1 :(得分:0)
例如:
public static void main(String[] args) {
int count = countChars("hello", 'l');
System.out.println(count);
}
答案 2 :(得分:0)
您的主要方法应该调用函数:
String string = "whatever";
char searchChar = "w";
System.out.println(countChars(string, searchChar));
答案 3 :(得分:0)
你可以这样做:
#include <iostream>
int main()
{
// perform 3 dimensionally nested iterations
// each index goes from 0 to 10
// so 10x10x10 iterations performed
meta_for<3, 0, 10>([&](size_t i, size_t j, size_t k)
{
std::cout << i << ' ' << j << ' ' << k << '\n';
});
return 0;
}
附注:你不需要countChars中的ch变量,你可以通过在同一行上将count设置为0来保存一些行,并在for语句中声明i。你可以这样做:(有些人喜欢保留{},而不是为/ if在同一条线上做)
public static void main(String[] args)
{
System.out.println(countChar("cheese", 'e'));
}
答案 4 :(得分:0)
您可以将返回值分配给变量:
String myString = "Count up the u's!";
char myChar = 'u';
int val = countChars(myString, myChar);
System.out.println(val);
或者您可以将该方法放在println方法中:
System.out.println("Count up the u's!", 'u');
查看Javadocs:https://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#println(int) println()方法可以打印字符串的文字或任何原始数据类型。希望这会有所帮助:)