Я пытаюсь реализовать тестер анаграмм на C. При вызове программы пользователь вводит два слова в двойных кавычках, например «слушай» и «молчи». Я почти заставил его работать, но у меня возникли проблемы с вспомогательной функцией, которую я написал, чтобы избавиться от пробелов в двух входных словах. Вот код этой функции:
void noSpaces(char word[100]) {
/*
This is a function to get rid of spaces in a word
It does this by scanning for a space and shifting the
array elements at indices > where the space is
down by 1 as long as there is still a space
there.
*/
for (int i = 0; i < 100; i++) {
while (word[i] == ' ') {
for (int j = i; j < 100; j++) {
word[j] = word[j+1];
}
}
}
}
Теперь он отлично работает, когда я передаю входное слово из функции main
этому помощнику. Проблема заключается во втором вызове этой функции. Когда я вызываю эту функцию для второго ввода, если k
— это количество пробелов в первом вводе, то функция стирает первые k
буквы второго ввода. Например, ввод ./anagram " banana" "banana"
даст мне ложный отрицательный результат, и если я добавлю оператор печати, чтобы увидеть, что происходит с входными данными после того, как на них вызывается noSpaces
, я получаю следующее:
banana
anana
Вот код полной программы:
#include <stdio.h>
int main(int argc, char *argv[]) {
//this if statement checks for empty entry
if (isEmpty(argv[1]) == 0 || isEmpty(argv[2]) == 0) {
//puts("one of these strings is empty");
return 1;
}
//call to noSpaces to eliminate spaces in each word
noSpaces(argv[1]);
noSpaces(argv[2]);
//call to sortWords
sortWords(argv[1]);
sortWords(argv[2]);
int result = compare(argv[1], argv[2]);
/*
if (result == 1) {
puts("Not anagrams");
} else {
puts("Anagrams");
}
*/
return result;
}
int compare(char word1[100], char word2[100]) {
/*
This is a function that accepts two sorted
char arrays (see 'sortWords' below) and
returns 1 if it finds a different character
at entry i in either array, or 0 if at no
index the arrays have a different character.
*/
int counter = 0;
while (word1[counter] != '\0' && word2[counter] != '\0') {
if (word1[counter] != word2[counter]) {
//printf("not anagrams\n");
return 1;
}
counter++;
}
// printf("anagrams\n");
return 0;
}
void sortWords(char word[100]) {
/*
This is a function to sort the input char arrays
it's a simple bubble sort on the array elements.
'sortWords' function accepts a char array and returns void,
sorting the entries in alphabetical order
being careful about ignoring the 'special character'
'\0'.
*/
for (int j = 0; j < 100; j++) {
int i = 0;
while (word[i + 1] != '\0') {
if (word[i] > word[i + 1]) {
char dummy = word[i + 1];
word[i + 1] = word[i];
word[i] = dummy;
}
i++;
}
}
}
void noSpaces(char word[100]) {
/*
This is a function to get rid of spaces in a word
It does this by scanning for a space and shifting the
array elements at indices > where the space is
down by 1 as long as there is still a space there.
*/
for (int i = 0; i < 100; i++) {
while (word[i] == ' ') {
for (int j = i; j < 100; j++) {
word[j] = word[j + 1];
}
}
}
}
int isEmpty(char word[100]) {
// if a word consists of the empty character, it's empty
//otherwise, it isn't
if (word[0] == '\0') {
return 0;
}
return 1;
}
Я знаю, что есть библиотека, которая может работать со строками, но я действительно хотел бы избежать ее использования. Я уже зашел так далеко, не нуждаясь в этом, и я чувствую, что проблема в основном решена, но есть одна маленькая вещь, которую я не вижу.
Я пришел из java, и я новичок в C, если это объясняет какую ошибку я сделал.
j
равно 99, вы получаете доступ кword[j+1]
, то естьword[100]
. Ноword[100]
нет, потому чтоword
имеет только 100 записей. - person David Schwartz   schedule 16.02.2019