![](/img/trans.png)
[英]Program to reverse order of words in a string printing reversed string incorrectly
[英]Finding a reversed words in a given string using C program
實際上,我已經搜索了超過 1 周的時間來找到使用 C 在給定字符串中查找反向單詞的解決方案。我的問題是,我得到了一個像“bakelovekac”這樣的字符串。 在這里,我在字符串中有一個“ake”的反向單詞為“eka”。 現在我需要在給定的字符串中找出這個反轉的單詞並打印出來。 怎么做到呢? 提前致謝!
一個基本的方法是迭代字符串的所有字符,並檢查每個字符是否重復,如果是,則檢查是否存在可能的反向字符串。
上述方法的粗略代碼如下所示:
#include <stdio.h>
void checkForRevWord(char *str, char *rev){
int length = 0;
while(1){
if(str >= rev)
break;
if(*str != *rev)
break;
length++;
str++;
rev--;
}
if(length > 1){
while(length--)
printf("%c", *(rev+length+1));
printf("\n");
}
return;
}
int main()
{
char *inputStr = "bakelovekac";
char *cur = inputStr;
char *tmp;
while(*cur != '\0'){
tmp = cur+1;
/* find if current char gets repeated in the input string*/
while(*tmp != '\0'){
if(*tmp == *cur){
checkForRevWord(cur, tmp);
}
tmp++;
}
cur++;
}
}
通過這個程序
#include <stdio.h>
#include <string.h>
int main()
{
char text[50]; //this character array to store string
int len,i;
printf("Enter a text\n");
scanf("%[^\n]s",text);//getting the user input with spaces until the end of the line
len=strlen(text);//getting the length of the array and assigning it the len variable
for(i=len-1;i>=0;i--)
{
printf("%c",text[i]); //printing the text from backwards
}
return 0;
}
謝謝你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.