zoukankan      html  css  js  c++  java
  • C语言编程练习7:字符串反转

    思路:遇到空格就输出空格前的字符串,最后一个字符串单独输出

    不用栈

    #include <iostream>
    #include <cstring>
    using namespace std;
    
    int main()
    {
    	char s[1005];
    	int n;
    	cin >> n;
    	getchar();
    	while (n--)
    	{
    		gets(s);
    		int k = 0;
    		int m = strlen(s);
    		for (int i = 0; i < m; i++)
    		{
    			if (s[i] == ' ')
    			{
    			    for (int j = i - 1; j >= k; j--)
    				{
    					cout << s[j];
    				}
    				cout << " ";
    				k = i + 1;
    			}
    		}
    		for (int i = m - 1; i >= k; i--)
    		{
    			cout << s[i];
    		}
    		cout << endl;
    	}
    }
    

     用栈

    #include <iostream>
    #include <cstdio>
    #include <string>
    #include <algorithm>
    #include <stack>
    
    using namespace std;
    
    int main()
    {
        int n;
        cin>>n;
        getchar();
        while(n--)
        {
            string s;
            getline(cin,s);
            int len;
            len = (int)s.size();
            stack<char>st;
            for(int i=0;i<len;i++)
            {
                if(s[i]!=' ')
                {
                    st.push(s[i]);
                }
                if(s[i]==' '||i==len-1)
                {
                    while(!st.empty())
                    {
                        printf("%c",st.top());
                        st.pop();
                    }
                    if(s[i]==' ')
                    {
                        printf(" ");
                    }
    
                }
            }
            printf("
    ");
        }
        
        
        return 0;
    }
    
  • 相关阅读:
    函数探幽--引用变量
    函数探幽—内联函数
    我遇到的头文件
    继承的特点
    汇编语言中压栈与入栈
    cin.good(),cin.fail(),cin.clear()
    结构体的处理(以c++primer plus 第六章习题4为例)
    uva508
    uva253 CubePainting
    uva1590
  • 原文地址:https://www.cnblogs.com/FantasticDoubleFish/p/14310140.html
Copyright © 2011-2022 走看看