一道Google2009夏季实习生招聘笔试程序设计题
要求:写一个函数void count(char* input,int len),此函数的功能是计算出一个字符串中每个字符的个数,不区分大小写,输出结果时按字符在字符串中出现的先后顺序。使用程序语言不限。例如:input="abCc*b",输出结果是a:1 b:2 c:2 *:1
本人实现的Java版本如下:
public class CountTest {
public static void main(String[] args) {
String input="abCc*b";
count(input,6);
}
private static void count(String input,int len){
String strVisited=null;
int num=0;
for(int i=0;i<len;i++){
char ch=Character.toLowerCase(input.charAt(i));
if(strVisited==null){
strVisited+=ch;
}else if(strVisited.indexOf(ch)==-1){
strVisited+=ch;
}else{
continue;
}
for(int j=0;j<len;j++){
if(Character.toLowerCase(input.charAt(j))==ch)
num++;
}
System.out.print(ch+":"+num+" ");
num=0;
}
}
}
public static void main(String[] args) {
String input="abCc*b";
count(input,6);
}
private static void count(String input,int len){
String strVisited=null;
int num=0;
for(int i=0;i<len;i++){
char ch=Character.toLowerCase(input.charAt(i));
if(strVisited==null){
strVisited+=ch;
}else if(strVisited.indexOf(ch)==-1){
strVisited+=ch;
}else{
continue;
}
for(int j=0;j<len;j++){
if(Character.toLowerCase(input.charAt(j))==ch)
num++;
}
System.out.print(ch+":"+num+" ");
num=0;
}
}
}
C++版本如下:
#include <stdlib.h>
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
void count(char *input, int len) {
string strVisited;
int num = 0;
for (int i = 0; i < len; i++) {
char ch = tolower(input[i]);
if (strVisited.empty()) {
strVisited += ch;
} else if (strVisited.find(ch, 0) == string::npos) {
strVisited += ch;
} else {
continue;
}
for (int j = 0; j < len; j++) {
if (tolower(input[j]) == ch)
num++;
}
cout << ch << ":" << num << " ";
num = 0;
}
}
int main(int argc, char** argv) {
string input="abCc*b";
count((char*)input.c_str(),6);
return (EXIT_SUCCESS);
}
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
void count(char *input, int len) {
string strVisited;
int num = 0;
for (int i = 0; i < len; i++) {
char ch = tolower(input[i]);
if (strVisited.empty()) {
strVisited += ch;
} else if (strVisited.find(ch, 0) == string::npos) {
strVisited += ch;
} else {
continue;
}
for (int j = 0; j < len; j++) {
if (tolower(input[j]) == ch)
num++;
}
cout << ch << ":" << num << " ";
num = 0;
}
}
int main(int argc, char** argv) {
string input="abCc*b";
count((char*)input.c_str(),6);
return (EXIT_SUCCESS);
}