簡體   English   中英

將小寫的字符串轉換為大寫? 在C中

[英]Convert string of lower case to upper case? In C

我的教授給了我一些用C語言進行的練習...在其中之一中,我必須將字符串作為參數傳遞給一個函數,該函數將驗證數組中是否存在小寫字母並將其轉換為大寫字母。

其實有一個函數可以做這樣的事情,但是我不能使用string.h。

有人有想法嗎?

void converterup(char palavra[])
{
    int i;

    for(i = 0; i < 10; i++)
    {
        if(palavra[i] != 'a')
        {
            palavra[i] == 'A';
        }
    }

會是這樣嗎?

您需要在使用toupper函數之前包含<ctype.h> ,然后像下面的示例一樣使用它(我編輯了您的代碼,需要根據需要對其進行調整):

for(i = 0; i < 10; i++){
    palavra[i] = toupper(palavra[i]);
}

此循環會將10個前幾個字符轉換為它們的上等ascii值

或者如果您不能使用標准功能,則可以使用如下功能:

char myUpperChar(char x){
    const int delta = 'a' - 'A'; //'a' has ascii code 97 while 'A' has code 65
    if(x <= 'z' && x >= 'a'){
        x -= delta;
    }
    return x;
}

如果字符在“ a”和“ z”之間,則只需在其上添加('A'-'a')即可將其轉換為大寫。

char input, output;
int diff = 'A' - 'a';

output = input;
if ('a' <= input && input <= 'z')
  output += diff;

return output;

我想您的教授期待沒有這種外部功能的更基本的東西。

char str[] = "hello";
int len = sizeof(str) / sizeof(char);
int i;
for(i = 0; i < len; i++) {
    int ascii = str[i];
    if(ascii >= 97 && ascii <= 122) {// 97 => 'a' and 122 => 'z' in ascii
        str[i] = (char) (ascii - 32); // 32 is the ascii substraction of lower 
    }                             // and upper letters 'a' - 'A'
}

然后輸出將是:

HELLO

函數將驗證數組中是否存在小寫字母,並將其轉換為大寫字母;

我不能使用string.h。

然后,您必須自己進行轉換。 看一下ASCII圖表。 然后您會注意到小寫和大寫字母相隔0x40 0x40恰好是空格' ' ;

遍歷數組並僅轉換小寫字母

arr[i] <= 'z' && arr[i] >= 'a'

記得小和大寫字母' '分開。

arr[i] = arr[i] - ' ' ;

通過增加索引i++前進到數組中的下一個字符,並在遇到字符串arr[i]=='\\0'的末尾時停止。

#include <stdio.h>

void converterup(char arr[])
{
    size_t i = 0;

    if(arr == NULL) return;

    while(arr[i]) // loop till the '\0'; this is equivalent to `arr[i]!='\0'`
    {
        if(arr[i] <= 'z' && arr[i] >= 'a'){
          arr[i] = arr[i] - ' ' ;
        }

        i++;
    }
}

int main(void)
{
    char str[] = "Hello World!";

    converterup(str);

    printf("%s",str);

    return 0;
}

測試:

HELLO WORLD! 

看看我的代碼專家,可以接受嗎?

#include <stdio.h>
#include <stdlib.h>
#include <locale.h>

    void strupr(char palavra[])
    {
        int i;

        for(i = 0;palavra[i] > 60 && palavra[i] < 122; i++)
        {
            printf("%c", palavra[i] - 32);
        }
    }

    int main(void)
    {
        setlocale(LC_ALL, "");
        char palavra[10];

            printf("Insira uma palavra maiúsculas: "); gets(palavra);
            printf("Valor com conversão: ");
            strupr(palavra);


        return 0;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM