在 C 函式內部,我基本上是在嘗試將 func 引數的所有值轉換為大寫。然后在函式的其他地方使用該引數。我不想更改傳遞給函式的變數。只是當地的論點。引數是一個字符陣列。
這是我嘗試過的:
int calculate_score(char *word[])
{
for (int i = 0, n = strlen(word); i < n; i )
{
if (islower(word[i]) != 0)
{
//this piece of code is not working
toupper(word[i]);
}
}
我該如何做到這一點?
編輯:我已經包含了所有必要的頭檔案字串和 ctype 以使其作業
uj5u.com熱心網友回復:
如果您不想更改引數字串,則應制作一個副本以供本地使用:
- 如果此字串有合理的最大長度,則可以使用 ; 的本地陣列
char。 - 否則您可以為副本分配記憶體并
- 使用回圈將內容轉換為大寫
- 并在回傳之前釋放此副本(如果已分配)
請注意,引數不應該是char *word[],而是char *word或更好const char *word。
這是一個例子:
#include <errno.h>
#include <stdlib.h>
#include <string.h>
int calculate_score(const char *word) {
int res = 0;
size_t i, n = strlen(word);
char *copy = malloc(n 1);
if (copy == NULL) {
fprintf(stderr, "calculate_score: allocation error\n");
return -1;
}
for (i = 0; i < n; i ) {
unsigned char c = word[i];
copy[i] = (char)toupper(c);
}
copy[i] = '\0';
// use copy for the computation
[...]
free(copy);
return res;
}
uj5u.com熱心網友回復:
如果您不想更改傳遞給函式的字串,請對其進行復制并進行處理。
void foo(char *bar) {
char *s = strdup(bar);
// do something to s
// bar remains unchanged
// don't forget to free that memory.
free(s);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/446396.html
下一篇:尋找有效的字串替換演算法
