C 编程 - 反转字符串

标签 c arrays function

在这个程序中,我尝试使用 2 个数组来反转字符串: 这里的问题是程序一直将字符“P”写为唯一的输出,我似乎无法弄清楚如何解决这个问题。

#include<stdio.h>
#include<string.h>
#define TAM 256

int get_string(char string[TAM]);    
int invert_string(char string[TAM]);    
int string_out(char string[TAM]);

int main(){
    char string[TAM]={0};  // always initialize a string to be completely zero, or unexpected behaviour may occur    
    get_string(string);
    invert_string(string);

    return 0;
}

int get_string(char string[TAM]){
    printf("Enter a string: ");
    scanf("%s",string);
    return 0;
}

int invert_string(char string[TAM]){
    char temporary_string[TAM]={0};
    int i,j;

    for(i=TAM,j=0;i>=0;i--){
        if(string[i]== ' '){
            continue;
        }else{
            temporary_string[j] = string[i];
            j++;
        }
    }
    printf("debug : temp string is : %s",temporary_string);
    return 0;
}

int string_out(char string[TAM]){
    printf("%s",string);
    return 0;
}

最佳答案

invert_string 函数中尝试这段代码:

int i,j;
for(i=strlen(string)-1,j=0;i>=0;i--){ // u can take variable and save length or directly pass length
    if(string[i]== ' '){
        continue;
    }else{
        temporary_string[j++] = string[i];
    }
}
temporary_string[j] = '\0';   //Make last index NULL
printf("%s",temporary_string);

关于C 编程 - 反转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27740742/

相关文章:

c - 当达到 char 值时,我的 struct c 编程崩溃了

c - 如何检查数组中是否有空闲位置,然后在该位置添加对象?

sql - Ruby + Sequel - 将数组序列化为文本数组的查询

c++ - 定义常量数组以用作模板参数

bash - 如何使用 bash 将函数的输出分配给变量?

python - 在 Python 中使用类根据用户输入打印出实例属性

C 将char数组(字符串)UTF8格式转换为CP1252(ASCII)格式

c - K&R C 书中的基本 getchar() 相关函数不起作用?

javascript - 将参数关闭函数添加到 JavaScript 中的字符串

为无堆的 32 位微 Controller 编译 zbar 库