我正在尝试查找、反转和替换一个句子中的单词。单词和句子可以自由更改。我们可以手动编写它们,也可以由用户编写它们。
在main()
中,我无法访问和获取反转函数的输出。编译器没有给予任何错误,但也没有显示任何输出。我不允许使用<stdio.h>
以外的任何库。我该怎么办?
#include <stdio.h>
int stringLength(char string[100]) {
int i, l = 0;
for (i = 0; string[i] != '\0'; i++) {
l++;
}
int length = l;
return length;
}
char reversing(char *givenWord[]) {
int i = 0, j = 0, k = 0;
char temp;
j = stringLength(*givenWord) - 1;
while (i < j) {
temp = *givenWord[i];
*givenWord[i] = givenWord[j];
*givenWord[j] = temp;
i++;
j--;
}
return *givenWord;
}
int compare(char *x, char *y) {
while (*x != '\0' || *y != '\0') {
if (*x == *y) {
x++;
y++;
}
// if they are not equal
else
if ((*x == '\0' && *y != '\0') || (*x != '\0' && *y == '\0') ||
*x != *y) {
return 0;
}
}
return 1;
}
int lenght(char *a) {
char *b;
for (b = a; *a; a++)
;
return a - b;
}
char *substring(char *main_string, char *substring) {
while (*main_string != '\0') {
char *p = main_string;
char *q = substring;
while (*p++ == *q++) {
if (*p == ' ' || *p == '\0')
if (*q == '\0') {
return main_string;
}
}
main_string++;
}
return NULL;
}
void replace_string_add(char *s, char *change_what, char *into_what, int shift)
{
char *i_pointer = into_what;
char *c_pointer = change_what;
char *position = substring(s, change_what);
while (position != NULL) {
char *end = position;
while (*end != '\0') {
end++;
}
while (end > position) {
*(end + shift) = *end;
end--;
}
while (*into_what != '\0') {
*position++ = *into_what++;
}
position = substring(s, change_what);
into_what = i_pointer;
change_what = c_pointer;
}
}
void replace_string_remove(char *s, char *change_what, char *into_what,
int shift)
{
char *i_pointer = into_what;
char *c_pointer = change_what;
char *position = substring(s, change_what);
while (position != NULL) {
char *temp = position;
while (*(temp + shift) != '\0') {
*temp = *(temp + shift);
temp++;
}
*temp = '\0';
while (*into_what != '\0') {
*position++ = *into_what++;
}
position = substring(s, change_what);
into_what = i_pointer;
change_what = c_pointer;
}
}
void replace_string(char *s, char *change_what, char *into_what)
{
int shift = lenght(into_what) - lenght(change_what);
if (compare(change_what, into_what) == 0) {
if (shift >= 0) {
replace_string_add(s, change_what, into_what, shift);
} else {
replace_string_remove(s, change_what, into_what, -shift);
}
}
}
int main() {
char s[] = "This is the input sentence", change_what[] = "input";
reversing(change_what);
char *word = reversing(change_what);
char into_what = ("%s", word);
replace_string(s, change_what, &into_what);
printf("\"%s\"", s);
return 0;
}
我尝试添加其他字符串并将它们声明为reverse函数的输出。
2条答案
按热度按时间rxztt3cl1#
我相信这段代码解决了你的问题。函数中有注解,抱歉我的英语不好
5hcedyr02#
你的代码太复杂了:
main
函数中,读取一个句子和一个单词,执行替换并输出修改后的句子。以下是一个简化版本: