2. 反转单词的两种解决方案
编写一个函数,反转一个字符串中单词的顺序。例如,函数应该将字符串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. 专用的解决方法:
专用解决方法的原理如下:
首先,将整个字符串进行反转。然后,对反转后的每个单词进行反转。与通用解决方法相比,专用解决方法的好处是不需要缓冲区。
程序代码如下:
#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;
}
程序的执行结果如下:

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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.

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.

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.

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

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.

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.

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.

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.
