Home Database Mysql Tutorial 2. 反转单词的两种解决方案

2. 反转单词的两种解决方案

Jun 07, 2016 pm 03:48 PM
function word reverse string write solution

编写一个函数,反转一个字符串中单词的顺序。例如,函数应该将字符串Life is better and better.转换成better. and better is Life。假定所有的单词都是以空格分隔的,标点也作为字母一样处理。 1. 通用的解决方法 通用解决方案的工作原理如下: 首先,需要

    编写一个函数,反转一个字符串中单词的顺序。例如,函数应该将字符串“Life is better and better.”转换成“better. and better is Life”。假定所有的单词都是以空格分隔的,标点也作为字母一样处理。

 

    1. 通用的解决方法

    通用解决方案的工作原理如下:

    首先,需要分配适当大小的临时缓冲区。然后,需要进行扫描循环,从字符串的最后一个字符开始。当发现非单词字符时,可以将它直接写到缓冲区中去。但是,当发现单词字符时,不能立即将它写入临时缓冲区。因为是在反向扫描这个字符串,遇到的第一个字符,正好是这个单词的最后一个字符,所以如果按发现字符的顺序复制,会使每个单词中的字符发生反转。所以,需要继续扫描,直到找到这个单词的第一个字符,再将这个单词的每个字符以正确的、不反转的顺序进行复制。当复制一个单词的字符时,需要确定这个单词的结尾,这样才能知道何时停止复制。可以通过检查每个字符是否是单词字符来实现这一点,但因为已经知道了这个单词最后一个字符的位置,更好的方法是进行复制直至到达这个位置。

    程序代码如下:

    #include "stdafx.h"
    #include
    #include

    #include

 

    bool reverseWords(char str[])
    {
        char *buffer;
        int tokenReadPos, wordReadPos, wordEnd, writePos = 0;

 

        // Position of the last character is length - 1
        tokenReadPos = strlen(str) - 1;

        buffer = (char*)malloc(tokenReadPos + 2);


        if(!buffer)
            return false; // reverseWords failed

 

        while(tokenReadPos >= 0)
        {
            if(str[tokenReadPos] == ' ') // Non-word characters
            {
                // Write character
                buffer[writePos++] = str[tokenReadPos--];
            }
            else // Word character
            {
                // Store position of end of word
                wordEnd = tokenReadPos;

 

                // Scan to next non-word character
                while(tokenReadPos >= 0 && str[tokenReadPos] != ' ')
                    tokenReadPos--;

 

                // tokenReadPos went past the start of the word
                wordReadPos = tokenReadPos + 1;

 

                // Copy the characters of the word
                while(wordReadPos                 {
                    buffer[writePos++] = str[wordReadPos++];
                }
            }
        }

 

        // null terminate buffer and copy over str
        buffer[writePos] = '/0';


        strcpy(str, buffer);

 

        free(buffer);

 

        return true; // ReverseWords successful
    }

 

    int main()
    {
         char str[] = "Life is better and better!";

         cout          reverseWords(str);
         cout

         return 0;
    }

 

    程序的运行结果如下图所示:

2. 反转单词的两种解决方案

 

 

2. 专用的解决方法:

    专用解决方法的原理如下:

    首先,将整个字符串进行反转。然后,对反转后的每个单词进行反转。与通用解决方法相比,专用解决方法的好处是不需要缓冲区。 

    程序代码如下:

    #include "stdafx.h"
    #include
    #include

 

    void reverseString(char str[], int start, int end)
    {
        char temp;
        while(end > start)
        {
            // Exchange characters
            temp = str[start];
            str[start] = str[end];
            str[end] = temp;

 

            // Move indices towards middle
            start++; end--;
         }
     }

 

     void reverseWords(char str[])
     {
         int start = 0, end = 0, length;

 

         length = strlen(str);

 

         // Reverse entire string
         reverseString(str, start, length - 1);

 

         while(end          {
             if(str[end] != ' ') // Skip non-word characters
             {
                 // Save positions of beginning of word
                 start = end;

 

                 // Scan to next non-word character
                 while(end                      end++;

                 // Back up to end of word
                 end--;

 

                 // Reverse word
                 reverseString(str, start, end);
              }
              end++; // Advance to next token
         }

    }

 

    int main()
    {
        char str[] = "Life is better and better!";

        cout         reverseWords(str);
        cout

        return 0;
     }

 

    程序的执行结果如下:

2. 反转单词的两种解决方案

 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Implementing Machine Learning Algorithms in C++: Common Challenges and Solutions Implementing Machine Learning Algorithms in C++: Common Challenges and Solutions Jun 03, 2024 pm 01:25 PM

Common challenges faced by machine learning algorithms in C++ include memory management, multi-threading, performance optimization, and maintainability. Solutions include using smart pointers, modern threading libraries, SIMD instructions and third-party libraries, as well as following coding style guidelines and using automation tools. Practical cases show how to use the Eigen library to implement linear regression algorithms, effectively manage memory and use high-performance matrix operations.

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

Java framework security vulnerability analysis and solutions Java framework security vulnerability analysis and solutions Jun 04, 2024 pm 06:34 PM

Analysis of Java framework security vulnerabilities shows that XSS, SQL injection and SSRF are common vulnerabilities. Solutions include: using security framework versions, input validation, output encoding, preventing SQL injection, using CSRF protection, disabling unnecessary features, setting security headers. In actual cases, the ApacheStruts2OGNL injection vulnerability can be solved by updating the framework version and using the OGNL expression checking tool.

What are the benefits of C++ functions returning reference types? What are the benefits of C++ functions returning reference types? Apr 20, 2024 pm 09:12 PM

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

See all articles