Skip to content

1. Parse nice int from char problem

DESCRIPTION

You ask a small girl,"How old are you?" She always says, "x years old", where x is a random number between 0 and 9.

Write a program that returns the girl's age (0-9) as an integer.

Assume the test input string is always a valid string. For example, the test input may be "1 year old" or "5 years old". The first character in the string is always a number.

Solution

cpp
#include <string>

int get_age(const std::string& she_said) {
    return she_said[0] - '0';
}

在C++中,可以使用 std::string 的下标操作符来访问字符串中的特定字符。 由于年龄总是在字符串的第一个字符,可以直接访问并转换它。

这段代码中,she_said[0]会得到字符串的第一个字符,它是一个数字字符。 由于字符实际上是以它们的ASCII码存储的,所以从该字符中减去字符'0'的ASCII码会得到实际的整数值。 例如,如果字符是'5',那么'5' - '0'的结果是整数5。

需要熟悉cpp std 的使用!

2. altERnaTIng cAsE <=> ALTerNAtiNG CaSe

DESCRIPTION

Define String.prototype.toAlternatingCase (or a similar function/method such as to_alternating_case/toAlternatingCase/ToAlternatingCase in your selected language; see the initial solution for details) such that each lowercase letter becomes uppercase and each uppercase letter becomes lowercase.

For example:

cpp
"hello world".toAlternatingCase() === "HELLO WORLD"
"HELLO WORLD".toAlternatingCase() === "hello world"
"hello WORLD".toAlternatingCase() === "HELLO world"
"HeLLo WoRLD".toAlternatingCase() === "hEllO wOrld"
"12345".toAlternatingCase()       === "12345"                   // Non-alphabetical characters are unaffected
"1a2b3c4d5e".toAlternatingCase()  === "1A2B3C4D5E"
"String.prototype.toAlternatingCase".toAlternatingCase() === "sTRING.PROTOTYPE.TOaLTERNATINGcASE"

As usual, your function/method should be pure, i.e. it should not mutate the original string.

Sulotion

遍历字符串中的每个字符,判断它是大写还是小写字母,然后进行相应的转换。 在C++中,可以使用std::islowerstd::isupper来检查一个字符的大小写, 使用std::tolowerstd::toupper来转换字符的大小写。

下面是完成的代码:

cpp
#include <string>
#include <cctype> // For std::tolower and std::toupper

std::string to_alternating_case(const std::string& str)
{
    std::string result;
    result.reserve(str.size()); // 优化,预分配足够的空间

    for (char c : str) {
        if (std::islower(c)) {
            // 如果字符是小写,则转为大写
            result += std::toupper(c);
        } else if (std::isupper(c)) {
            // 如果字符是大写,则转为小写
            result += std::tolower(c);
        } else {
            // 如果字符不是字母,则保持不变
            result += c;
        }
    }
    
    return result;
}

在这段代码中,result字符串被用来存储转换后的结果。 使用reserve函数来避免在字符串连接操作中多次重新分配内存。

字符串中的每个字符都被检查: 如果它是小写字母,就转换为大写字母; 如果它是大写字母,就转换为小写字母; 如果它不是字母,就保持不变。

最终,转换后的字符串被返回。

3. Correct the mistakes of the character recognition software

DESCRIPTION

Character recognition software is widely used to digitise printed texts. Thus the texts can be edited, searched and stored on a computer.

When documents (especially pretty old ones written with a typewriter), are digitised character recognition softwares often make mistakes.

Your task is correct the errors in the digitised text. You only have to handle the following mistakes:

  • S is misinterpreted as 5
  • O is misinterpreted as 0
  • I is misinterpreted as 1

The test cases contain numbers only by mistake.

Solution

使用 std 自带的 replace()

cpp
#include <string>

std::string correct(std::string str){
  replace(str.begin(), str.end(), '5', 'S');
  replace(str.begin(), str.end(), '0', 'O');
  replace(str.begin(), str.end(), '1', 'I');
  return str;
}

直接遍历:

cpp
#include <string>

std::string correct(std::string str){
    //your code here
    for (char &c : str) {
        switch (c) {
            case '5': c = 'S'; break;
            case '0': c = 'O'; break;
            case '1': c = 'I'; break;
            default:
                break;
        }
    }
    return str;
}

4. Remove exclamation marks

DESCRIPTION

Write function RemoveExclamationMarks which removes all exclamation marks from a given string.

Solution

使用 std 自带的 erase()

cpp
#include <string>

std::string removeExclamationMarks(std::string str){
  str.erase(std::remove(str.begin(), str.end(), '!'), str.end());
  return str;
}

lamda 函数的方式:

cpp
#include <string>

std::string removeExclamationMarks(std::string str){
  //your code here
//   str.erase(std::remove(str.begin(), str.end(), '!'), str.end());
  str.erase(std::remove_if(str.begin(), 
                           str.end(), 
                           [](char c){ return c == '!'; }
                          ), 
            str.end());
  return str;
}

正则表达式:

cpp
#include <string>
#include <regex>

std::string removeExclamationMarks(std::string str){
  return std::regex_replace(str, std::regex ("!"), "");
}

5. String repeat

DESCRIPTION

Write a function that accepts an integer n and a string s as parameters, and returns a string of s repeated exactly n times.

Examples (input -> output)

bash
6, "I"     -> "IIIIII"
5, "Hello" -> "HelloHelloHelloHelloHello"

Solution

循环递加:

cpp
#include <string>

std::string repeat_str(size_t repeat, const std::string& str) {
    std::string result;
    result.reserve(repeat * str.size());
    
    for (int i=0; i < repeat; ++i)
        result += str;
    return result;
}
markdown

# X. tile
## DESCRIPTION
## Solution

基于 VitePress 构建