用户必须插入一个字符串,在该字符串中我必须计算不同的符号。例如:" Ellipse"有6个不同的符号,而整个单词有7个符号,不同的符号是:" E,l,i,p,s,e"。
我能够编写一个能够正确计算符号的代码,但是编写这些符号时我遇到了很大的问题! 请注意:我不允许使用任何其他库(例如string.h)。
#include <stdio.h>
#define MAX 256
int main()
{
int VOwels=0,diff=0,counter,i,j;
char vowels[]={'a','e','i','o','u','A','E','I','O','U'};
char sentence[MAX], diff_symbols[MAX];
printf("\nInsert sentence: ");
gets(sentence);
for(i=0;sentence[i]!='\0';i++){
if(i==0){
diff_symbols[i]=sentence[i];//first symbols is always saved
diff++;
}
counter=0;//Reset counter
if(i!=0){
for(j=0;diff_symbols[j]!='\0';j++){//checking if the symbol was already observed
if(sentence[i]==diff_symbols[j]){
counter++;
break;//as soon as we find the same symbol we stop checking
}
}
if(counter==0){//if we haven't found that symbol in the diff_symbols yet than
diff_symbols[j]=sentence[i];
diff++;
}
}
for(j=0;vowels[j]!='\0';j++){//counting vowels
if(sentence[i]==vowels[j]){
VOwels++;
break;
}
}
}
printf("Inserted sentence is: %s",sentence);
printf("\nThere are %d symbols in the string\n",i);
printf("There are %d different symbols in the string. The symbols are: %s\n",diff,diff_symbols);
printf("Number of vowels %d.\n",VOwels);
return 0;
}
结果几乎是好的。数字匹配,除非我试图写出所有不同的符号时发生了一些非常奇怪的事情 - 一些不应该存在的奇怪符号。
有什么想法吗? :/
答案 0 :(得分:1)
问题是diff_symbols
未初始化。如果设置char diff_symbols[256]={0}
,该程序可以正常工作。
一个更简单的算法是迭代字符串并打开diff_symbols
的单元格,如果字符串中出现相应的字符。然后遍历数组并打印字符iff相应的单元格是否打开。
答案 1 :(得分:0)
你在这里。:)
$user = $this->getDoctrine()
->getRepository('Bundle:CusUser')
->findOneBy(
array('username' => $user->getUsername(), 'email' => $user->getUsername(), 'password' => $user->getPassword())
);
如果要输入
#include <stdio.h>
#define MAX 256
int main( void )
{
const char *vowels = "aeiouAEU";
char diff_symbols[MAX] = { '\0' };
char sentence[MAX];
size_t total_cnt, diff_cnt, vowels_cnt;
size_t i;
printf( "\nInsert sentence: " );
fgets( sentence, MAX, stdin );
total_cnt = diff_cnt = vowels_cnt = 0;
for ( i = 0; sentence[i] != '\n' && sentence[i] != '\0'; i++ )
{
diff_symbols[( unsigned char )sentence[i]] = 1;
size_t j = 0;
while ( vowels[j] != '\0' && vowels[j] != sentence[i] ) ++j;
vowels_cnt += vowels[j] != '\0';
}
if ( sentence[i] == '\n' ) sentence[i] = '\0';
total_cnt = i;
for ( i = 0; i < MAX; i++ ) diff_cnt += diff_symbols[i];
printf( "\nInserted sentence is: %s\n", sentence );
printf( "There are %zu symbols in the string\n", total_cnt );
printf( "There are %zu different symbols in the string.", diff_cnt );
printf( "The symbols are: " );
for ( i = 0; sentence[i] != '\0'; i++ )
{
unsigned char c = sentence[i];
if ( diff_symbols[c] )
{
diff_symbols[c] = 0;
putchar( sentence[i] );
}
}
printf( "\n" );
printf( "Number of vowels %zu.\n", vowels_cnt );
return 0;
}
然后程序输出看起来
Ellipse
此外,您可以添加不计算例如空白字符的代码。