Domanda

How can I compare character regardless of its case. Means suppose I enter Z if my if condition shall return true for both Z and z, character can be any alphabet from A-Z or a-z.
Like ABCbabcAABC
If I enter B then it I must get 4 as output because there are 4 B in string.
I am learning C++ on Turbo C++. I am trying to do but now not getting way out.

void main()
{
    clrscr();

    char str[50],ch;
    char str1[50];

    int i = 0, l;

    cout << "Enter strings: ";
    gets(str);
    cout << "Enter charcter: ";
    cin >> ch;

    l = strlen(str);

    for(i = 0; i <= l; i++)
    {
        cout << isupper(str[i]) ? tolower(str[i]) : toupper(str[i]);
    }

    puts(str);
    getch();
}
È stato utile?

Soluzione

void main()
{
    clrscr();
    char str[50],ch;
    char str1[50];
    int i=0,l;
    cout<<"Enter strings: ";
    gets(str);
    cout<<"Enter charcter: ";
    cin>>ch;
    l=strlen(str);
    int result=0;
    for(i=0;i<l;i++)
    {
             if(tolower(ch)== tolower(str[i]))
        {
            result++;
        }
    }
puts(str);
puts(result);
getch();
}

Altri suggerimenti

if (tolower(str[i]) == tolower(ch)) {
    cout << (isupper(str[i]) ? tolower(str[i]) : toupper(str[i])); 
} else {
    cout << str[i];
}

40000 is the isupper output. Non zero for an upcase char, zero for lowercase, as written in manual

All you need to do is to play around with the ASCII value.

Check out the code: which explains that you need to convert only those characters whoce ASCII value is between 65(A) to 90(Z).

public class Ques2 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {
    //ascii A=65 Z=90 a=97
    System.out.println("Enter UPPERCASE");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   // String input = br.readLine().toLowerCase();
    char c;
    char[] word=br.readLine().toCharArray();
   for(int i :word)
   {
       if(i>=65 && i<=90){
       i=i+32 ;
       c=(char) i;
        System.out.println(c);
       }
       else{
           c=(char)i;
           System.out.println(c);
       }
   }

}

}

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top