华为机试——整理数字字符串

C_C++_XY_01.整理数字字符串

  • 题目描述:

输入一个包含若干整数的字符串,负数前面带有负号‘-’,正数不带‘+’,每个整数都是个位数

请将此串进行如下整理:

1、 将串中的正负数分离,使得负数在前,正数在后;

2、 分离后的正负数分别保持在原串中的相对顺序不变;

3、 输出参数为整理后的字符串。

当输入串格式非法,不作处理,直接输出原有字符串。

  • 要求实现函数:

void ArrangeString(const char *pInputStr, long lInputLen, char *pOutputStr);

【输入】 pInputStr: 输入字符串

lInputLen: 输入字符串长度

【输出】 pOutputStr: 输出字符串,空间已经开辟好,与输入字符串等长;

【注意】不用考虑输入串为空的情况

  • 示例

输入:“453-51-89-4”

输出:“-5-8-445319”

输入:“5--64”

输出:“5--64”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

#include <iostream>
#include <ctype.h>
#include <string.h>
using namespace std;
 
/*
* 抓住两点:1.要么是数字,要么是负号,其他都为无效输入。2.负号后一定是一个数字。
* 思路:1.判断是否是负号,是则判断负号后是否为数字,将这个负数保存。2.不是负号是数字,则将这个数作为正数保存。
* */
void ArrangeString(const char *pInputStr, long lInputLen, char *pOutputStr)
{
    if ((pInputStr == NULL) || (lInputLen <= 0) || (pOutputStr == NULL))
    {
        return;
    }
 
    const char *copyInput = pInputStr;
    char *positiveNum = new char[lInputLen];
    char *copyOutput = pOutputStr;
 
    for (int i = 0; i < lInputLen; i++)
    {
        if (isdigit(*copyInput)) //如果是数字。
        {
            *positiveNum = *copyInput;
            positiveNum++;
            copyInput++;
        }
        else //不是数字。
        {
            if (*copyInput == '-')//是负号。
            {
                *pOutputStr = *copyInput;
                pOutputStr++;
                copyInput++;
 
                if (isdigit(*copyInput)) //负号后一定是一个数字。
                {
                    *pOutputStr = *copyInput;
                    pOutputStr++;
                    copyInput++;
                }
                else //若不是,则是无效输入。
                {
                    strcpy(copyOutput, pInputStr);
                    return;
                }
            }
            else //不是数字,且不是负号,则是无效输入。
            {
                strcpy(copyOutput, pInputStr);
                return;
            }
        }
    }
}
 
int main() {
    char *test = "453-51-89-4";
    char *test2 = "a";
    char pOutputStr[20];
    ArrangeString(test2, strlen(test2), pOutputStr);
    cout << pOutputStr << endl;
 
    return 0;
}
原文地址:https://www.cnblogs.com/helloweworld/p/3200099.html