【问题标题】:I have a char array and I want to insert two more spaces for each space我有一个 char 数组,我想为每个空格再插入两个空格
【发布时间】:2019-07-13 04:37:32
【问题描述】:

我的逻辑如下:

#include<bits/stdc++.h>
    using namespace std;
    
    int main(){
        char a[50] = {'h','i',' ','m','e',' ','t','e'};
        
        
        // k = 4 because i have 2 spaces and for each
       // space i have to insert 2 spaces . so total 4 
       //spaces
        int k=4;
        for(int i=strlen(a)-1 ; i>0 && k >0 ; i--){
            if(a[i] != ' ')
            {
                a[i+k] = a[i];
                a[i] = ' ';
            }
            else
            {
                k = k - 2;
            }
            
        }
    
        printf("%s" , a);
    
        return 0;
    }

我必须用字符数组来解决它。我能够 使用字符串 stl 执行此操作 我得到的输出是 嗨---我。 但答案是 嗨---我---te。

【问题讨论】:

  • 一个问题是您没有正确地对结果字符串进行空终止,因此调用printf 可能会表现得很奇怪。用铅笔和纸逐步完成你的算法。您没有正确设置所有数组元素。
  • 无关:#include&lt;bits/stdc++.h&gt;loads the gunusing namespace std;takes the safety off。真的要小心。
  • 另一个好的策略是向Rubber Duck 解释程序中每一行的用途。橡皮鸭是出了名的愚蠢,所以你必须非常仔细地解释。有时,通过对话,橡皮鸭会引导您提出一些有趣的问题,例如当您执行 a[i+k] = a[i]; 时,a[i+k] 的数据会发生什么情况@

标签: c++ arrays char


【解决方案1】:

您的代码被标记为 C++。但是您的代码中没有任何 C++。纯C。

而且,您包括#include&lt;bits/stdc++.h&gt; 并使用std 命名空间 using namespace std;。从今以后:请你这辈子不要再做这种事了。或者,停止使用 C++。

另外,永远不要在 C++ 中使用像 char a[50] 这样的纯 C 样式数组。

在您的代码中存在一些错误。最关键的是缺少终止 0,然后调用strlen。在你使用一个函数之前,总是在某个地方检查这个函数是如何工作的。使用有意义的变量名。写 cmets。始终检查边界。

我更新了你的 C 代码:

#include <stdio.h>

int main()
{
    // Character String to work on
    char charString[50] = "hi me te";

    // Check all possible positions in string
    for (int index = 0; (index < 49) && (0 != charString[index]); ++index)
    {
        // If there is a space in the string
        if (' ' == charString[index])       
        {
            // Shift all characters one position to the right
            for (int shiftPosition = 48; shiftPosition >= index; --shiftPosition)
            {
                charString[shiftPosition + 1] = charString[shiftPosition];
            }
            ++index;
        }
    }
    // Show result
    printf("%s\n", charString);

    return 0;
}

这里是 C++ 解决方案

#include <iostream>
#include <string>
#include <regex>

int main()
{
    // Text to work on
    std::string text("hi me te");

    // Replace every space with 2 spaces. Print result
    std::cout << std::regex_replace(text, std::regex(" "), "  ");

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多