C语言 如何转换和更新字符串值在我的双链表成大写字母?


  • 假设我在双链表中有以下值:"香蕉、PEAR"。
  • 我怎样才能成功地将这些字符串转换为:"橙,香蕉,梨"。

用于将小写字符转换为大写字符的for循环应该运行直到它到达head->data中字符串的空字符,然后通过将该索引处的字符减去32以获得小写字符的大写ASCII值来检查它是否为小写将其转换为大写。一个朋友建议对它进行类型转换,但即使这样它也不会完全执行,它一直给我相同的输出。所以我不知道是什么问题。任何帮助或建议都很感激。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//My node structure
struct node 
{
char* data;
struct node *prev;
struct node *next;
};
//Declared two global variables
struct node* head = NULL;
struct node* tail = NULL;

// Function to insert at the front
// of the linked list
void insertAtEnd(char* data) {  
//Create a new node  
struct node *newNode = (struct node*)malloc(sizeof(struct node));  
newNode->data = data;  

//If list is empty  
if(head == NULL) {  
//Both head and tail will point to newNode  
head = tail = newNode;  
//head's previous will point to NULL  
head->prev = NULL;  
//tail's next will point to NULL, as it is the last node of the list  
tail->next = NULL;  
}  
else {  
//newNode will be added after tail such that tail's next will point to newNode  
tail->next = newNode;  
//newNode's previous will point to tail  
newNode->prev = tail;  
//newNode will become new tail  
tail = newNode;  
//As it is last node, tail's next will point to NULL  
tail->next = NULL;  
}  
}  

// The traverse list function
void traverse()
{
// List is empty
if (head == NULL) {
printf("nList is emptyn");
return;
}
// Else print the Data
struct node* temp;
temp = head;
while (temp != NULL) {
printf("%sn", temp->data);
temp = temp->next;
}
}
int main(int argc, char **argv){
insertAtEnd("Orange");
insertAtEnd("banana");
insertAtEnd("PEAR");
//converting each char in head->data into uppercase letter.
for (int i = 0; head->data[i]!=''; i++) {
printf("Entered outer loopn");
if((int)head->data[i] >= 97 && (int)head->data[i] <= 122) {
head->data[i] = (char)(((int)head->data[i]) - 32);
printf("Entered inner loopn");
}
}
traverse();
}

预期输出(在尝试将每个字符转换为大写并调用traverse()之后):

ORANGE
BANANA
PEAR

实际输出:

Entered outer loop
编辑:将所有代码连接在一起,以更好地复制和可读性。总的来说,我的目标是更新保存在双链表中的字符串,使其在不使用uppercase函数的情况下完全大写。因此,这就是为什么我最终试图使用那个for循环,据说它使用表中的ASCII值作为参考,从小写转换为大写。但是,由于某些原因,当我运行它时,它没有执行

你传递const char*给data,所以你不能转换它,你应该这样写:

struct node* tmp = head;
while(tmp) {
tmp->data = strdup(tmp->data);
for (int i = 0; tmp->data[i]!=''; i++) {
if(tmp->data[i] >= 97 && tmp->data[i] <= 122) {
tmp->data[i] = tmp->data[i] - 32;
}
}
tmp = tmp->next;
}
traverse();

不需要将char转换为int, char可以像整型一样使用

最新更新