Я новичок в программировании на C и пытаюсь написать простую функцию, которая будет нормализовать массив символов. В конце я хочу вернуть длину нового массива символов. Я прихожу из java, поэтому прошу прощения, если я делаю ошибки, которые кажутся простыми. У меня есть следующий код:Возвращение длины массива символов в C
/* The normalize procedure normalizes a character array of size len
according to the following rules:
1) turn all upper case letters into lower case ones
2) turn any white-space character into a space character and,
shrink any n>1 consecutive whitespace characters to exactly 1 whitespace
When the procedure returns, the character array buf contains the newly
normalized string and the return value is the new length of the normalized string.
*/
int
normalize(unsigned char *buf, /* The character array contains the string to be normalized*/
int len /* the size of the original character array */)
{
/* use a for loop to cycle through each character and the built in c functions to analyze it */
int i;
if(isspace(buf[0])){
buf[0] = "";
}
if(isspace(buf[len-1])){
buf[len-1] = "";
}
for(i = 0;i < len;i++){
if(isupper(buf[i])) {
buf[i]=tolower(buf[i]);
}
if(isspace(buf[i])) {
buf[i]=" ";
}
if(isspace(buf[i]) && isspace(buf[i+1])){
buf[i]="";
}
}
return strlen(*buf);
}
Как вернуть длину массива символов в конце? Также правильно ли моя процедура делает то, что я хочу?
EDIT: Я внесла некоторые исправления в свою программу на основе комментариев. Правильно ли сейчас?
/* The normalize procedure normalizes a character array of size len
according to the following rules:
1) turn all upper case letters into lower case ones
2) turn any white-space character into a space character and,
shrink any n>1 consecutive whitespace characters to exactly 1 whitespace
When the procedure returns, the character array buf contains the newly
normalized string and the return value is the new length of the normalized string.
*/
int
normalize(unsigned char *buf, /* The character array contains the string to be normalized*/
int len /* the size of the original character array */)
{
/* use a for loop to cycle through each character and the built in c funstions to analyze it */
int i = 0;
int j = 0;
if(isspace(buf[0])){
//buf[0] = "";
i++;
}
if(isspace(buf[len-1])){
//buf[len-1] = "";
i++;
}
for(i;i < len;i++){
if(isupper(buf[i])) {
buf[j]=tolower(buf[i]);
j++;
}
if(isspace(buf[i])) {
buf[j]=' ';
j++;
}
if(isspace(buf[i]) && isspace(buf[i+1])){
//buf[i]="";
i++;
}
}
return strlen(buf);
}
Используйте '» «'вместо'»«'' вернуть STRLEN (* ЬиЕ) 'должен быть' обратный STRLEN (BUF) ' – Machtl
В C, строка заканчивается ' '\ 0''. Использование 'len' подразумевает' buf' - массив 'unsigned char', не обязательно _string_. Выбери один. – chux
'if (isspace (buf [len-1])) {i ++; } 'является проблемой – chux