C程序将字符串大写不起作用

时间:2016-02-08 22:06:37

标签: c string

因此,对于作业,我必须完成一个用于大写字符串的代码。

我试过的是:

#include <stdio.h>

void capitalize(char *str)
{
    int i = 0;
    if (str[i] >= 97 && str[i] <= 122)
    {
        str[i] = str[i] - 32;
    }
    else
    {
        i++;
    }
}

void strCopy(char *str2, char *str1)
{
    while (*str2)
    {
      *str1 = *str2;
      str2++;
      str1++;
    }
    *str1 = '\0';
}

int main(int argc, char **argv)
{
    char string1[100] = "This is a really long string!";
    char string2[100];
    strCopy(string1,string2);
    capitalize(string2);
    printf("The original string is \"%s\"\n", string1);
    printf("The capitalized string is \"%s\"\n", string2);
}

然而,当我尝试运行它返回的代码时:

  

原始字符串是&#34;这是一个非常长的字符串!&#34;
  大写字符串是&#34;这是一个非常长的字符串!&#34;

strcopy似乎不是问题,因为它会将string1正确复制到string2

我不明白为什么capitalize无法正常工作,因为看起来应该逐字逐句地将其更改为大写,如果该字母属于小写字母的 ascii 代码。

我非常感谢有人帮助指出错误的位置。

提前致谢!

4 个答案:

答案 0 :(得分:7)

问题是您的capitilize功能没有循环。您只需将字符串的第一个字母大写。

你走在正确的轨道上,但你正在寻找的是:

for (int i = 0; str[i] != '\0'; ++i) { // Here we check for the end condition of a string.
                                       // ie. Has the Null termination been reached?
   if (str[i] >= 'a' && str[i] <= 'z') {
      str[i] = str[i] - ('a' - 'A');
   }
}

Here is a live demo for you to play with!

答案 1 :(得分:3)

您的capitalize()函数仅针对一个字符运行。试试这个

for (int i = 0 ; str[i] != '\0' ; ++i) {
    if (str[i] >= 97 && str[i] <= 122)
        str[i] = str[i] - 32;
}

每个角色执行操作,直到找到'\0'

答案 2 :(得分:1)

试试这个:

void capitalize(char *str)
{
    int i = 0;
    while (str[i] != '\0')
    {
      if (str[i] >= 97 && str[i] <= 122) {
          str[i] = str[i] - 32;
      }
      i++;
    }
}

答案 3 :(得分:0)

你需要修复 List<String> AccountList = new ArrayList<String>(); AccountList.add("45678690"); AccountList.add("7878787"); Scanner AccountInput = new Scanner(System.in); int x = 1; do{ try{ System.out.println("Hi whats your pin code?"); String Value = AccountInput.nextLine(); for (int counter = 0; counter < AccountList.size(); counter++){ if (AccountList.contains(Value)){ //If Input = ArrayList number then display "hi" System.out.println("Hi"); x = 2; } } } catch (Exception e){ System.out.println("You cant do that"); } }while (x==1); } } 来检查字符串的所有字符,而不仅仅是单个字符。使用指针可以避免包括capitalize(char *str)使用<string.h>函数,就像以下内容:

strlen()