CやC ++、文字、文字列、機密上の文字列変換

C言語を使用してまず、

(1)大文字と小文字

  • 方法a:ASCIIコードを使用して。
int main(){
    char c='a';
    char ch=c-32;
    printf("%c %c",c,ch);
    return 0;
}

出力:
ここに画像を挿入説明

  • 方法2:提供するC言語関数を使用して:toupper()和tolower()
    使用する必要があります#include<ctype.h>
#include<ctype.h>
int main(){
    char c='a';
    char ch=toupper(c);
    printf("%c %c",c,ch);
    return 0;
}

(2)小文字の文字列は、大文字になります

  • 方法a:変換。
int main(){
    char ch[]="hello world";
    int i=0;
    while(ch[i]!='\0'){
        if(ch[i]>='a'&&ch[i]<='z'){
            ch[i]-=32;
        }
        i++;
    }
    printf("%s",ch);
    return 0;
}

出力:
ここに画像を挿入説明

  • 方法2:使用するstrupr()和strlwr()機能
int main(){
    char ch[]="hello world";
    char* c=strupr(ch);
    printf("%s",c);
    return 0;
}






第二に、C ++の使用

(1)大文字の文字列内の小文字

  • 方法a:ASCIIコードを使用して。C言語。
int main(){
    string s="hello world";
    for(int i=0;i<s.size();i++){
        if(s[i]>='a'&&s[i]<='z'){
            s[i]-=32;
        }
    }
    cout<<s;
    return 0;
}
  • 方法二:の使用であるtoupper()和tolower()機能は、ここに備えるの#include <のctype.h>ヘッダファイル、直接必要はありません#include<iostream>には、
int main(){
    string s="hello world";
    for(int i=0;i<s.size();i++){
        if(s[i]>='a'&&s[i]<='z'){
            s[i]=toupper(s[i]);
        }
    }
    cout<<s;
    return 0;
}
  • 方法3トランスフォームを使用して結合TOLOWERとTOUPPER
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
    string first,second;
    cin>>first;
    second.resize(first.size());
    transform(first.begin(),first.end(),second.begin(),::toupper);
    cout<<second<<endl;
    return 0;
}

ここに画像を挿入説明
また、文字列の変換はご注意スペースを含めることはできません
ここに画像を挿入説明
この方法は多くありませんが、最初の2を使用することをお勧めします

公開された262元の記事 ウォン称賛15 ビュー8985

おすすめ

転載: blog.csdn.net/weixin_44123362/article/details/104115036