注册 登录
编程论坛 C++教室

初学者求助解答几个C++编程

迷途小羔羊 发布于 2008-11-05 00:14, 1049 次点击
1. (Occurences of a specified character) Write a function that finds the number of occurrences of a specified character in the string using the following header:
    Int count(const char * const str, char a)
For example, count(“Welcome”, ‘e’) returns 2.
prompt the user to enter a string and a letter


2. (Hex to decimal) Writer a function that parses a hex number as a string into a decimal integer. The function header is as follows:
    Int parseHex(const char * const hexString)
For example, hexString A5 is 165 (10x16+5=165) and FAA is 4100 (15x16^2+10x16+10=4100). So, parseHex (“A5”) returns 165 and parseHex(“FAA”) returns 4100. Use hex strings ABC and 10A to test the function.
prompt the user to enter a hexadecimal number


3. (Sorting characters in a string) Write two overloaded functions that return a sorted string using the following header:
    Char * sort(char *s)
    Void sort(const char * const s, char * s1)

For example, sort(“acb”) return abc.
you will have to allocate memory for the sorted array
4 回复
#2
taiyang03312008-11-05 10:54
NO.1
int count(const char * const str, char a)
{
    char const *p = str;
    int i = 1;

    while (*p++ != a)
    {
        i += 1;

        if(*p == '\0')
            return 0;
    }

    return i;
}
#3
taiyang03312008-11-05 11:35
NO.2
int parseHex(const char * const hexString)
{
    const char *dest = hexString;
    int value = 0;

    while('\0' != *dest)
    {
        switch(*dest)
        {
        case 'A':
            value += 10;
            break;
        case 'B':
            value += 11;
            break;
        case 'C':
            value += 12;
            break;
        case 'D':
            value += 13;
            break;
        case 'E':
            value += 14;
            break;
        case 'F':
            value += 15;
            break;
        default:
            value += atoi(dest);
            break;
        }        
        value *= 16;
    
        dest++;
    }

    return value / 16;
}
有点麻烦, 先想到这的  也是新手
#4
迷途小羔羊2008-11-05 23:16
看了这个终于有点头绪了````谢谢阿!!!!
#5
zxf126042008-11-06 10:44
#include <iostream>
using namespace std;
int fun(const char *const ,char );
void main()
{
    cout<<"输入一个单词:"<<'\n';
    char a[10];
    cin.getline(a, 10);
    
    const char *const str=&a[0];
    cout<<"输入要查的字母:"<<'\n';
    char p;
    cin>>p;
    int x=fun (str,p);
    cout<<x<<endl;


}
int fun (const char *const str,char n)
{   
    const char *z=str;
          int j=1;
    while (*z!=n)
    {
        j++;
        if(*z=='\0')
            return 0;
        z++;

    }
    return j;
    
}
1