문제

So.. I'm sorry I doubleposted. I really didn't know how this site works. However, I'm changing my whole question here so that it's more understandable. And here it is:

char s[1002];
cin.getline(s, 1002, '\n');
int k;
int p = strlen(s);
strcat(s, " ");

for (int i = 0; i <= p; i++)
{
    if (s[i] == ' ')
    {

        for (k = i - 1; (k != -1) && (s[k] != ' '); k--)
            cout << s[k];
        cout << " ";

    }
}

' ' , ',' , '.' and ';' should be delimiters but I've managed to pull it to work only with ' ' (intervals).

I cannot use std::string as I'm doing this for a homework where I need to make a very specific function - char const* reverseWordsOnly(const char*).

What should the code do?

Input: Reversing the  letters, is; really hard.

Output: gnisreveR eht  srettel, si; yllaer drah.
도움이 되었습니까?

해결책

While I still feel this is a duplicate, the thought process for solving this would be this:

  1. Write a function that returns true for alphabet characters (a-z and A-Z), and false otherwise.
  2. Start at the beginning of the string
  3. Find the next alphabet character, note its location (start)
  4. Find the next non-alphabet character, note its location (end)
  5. Reverse the characters in the range [start, end)
  6. Repeat steps 3-5 until the end of the string

All of this becomes very easy when you use std::string and algorithms like std::reverse instead of using raw arrays and custom. Since you are allowed to use std::cin and std::cout (<iostream>), the argument against using <string> is a silly one.

다른 팁

You can store the string in another array without the symbols first and then reverse the new array. For example if you want to ignore a comma (,) or semicolon (;) you can write something like

while(i <= p)
{
    if (s[i] == ',' || s[i] == ';')
    {
        i++;

    }
    else
    {
       temp[j]=s[i];
       j++;
       i++;
    }
 }

Then you can reverse the temp array.

Instead of just printing the letters like this

for (k = i - 1; (k != -1) && (s[k] != ' '); k--)
    cout << s[k];
cout << " ";

Check to see if you need to ignore the letter, like this

for (k = i - 1; (k != -1) && (s[k] != ' '); k--)
    if((s[k] != ',') && (s[k] != ';') && ...other ignored chars...)
       cout << s[k];
cout << " ";
#include<iostream>
#include<string>
#include<stdio.h>
using namespace std;

int main(){
    char s[1001],ch;
    int c=0;    // for counting how many words are in the array
    while((ch = getchar()) != '\n'){    // input string until new line
        if ((ch>='a' && ch<='z') || (ch>='A' && ch<='Z'))   // check if the input character is a letter or symbol
            s[c++] = ch;    // if its a letter then insert into the array
    }

    for (int i=c-1;i>=0;i--)    // print the array in reverse order
        cout<<s[i]<<" ";

    return 0;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top