簡體   English   中英

使用指針和冒泡排序反轉 c 中字符串的程序

[英]A program for inverting strings in c using pointers and bubble sort

我必須編寫一個接受字符串輸入並將其反轉的程序,因此基本上反轉文本。 我還想嘗試重用我的一個具有冒泡排序功能並認為它可以工作的代碼。

所以這是我的代碼:

#include <stdio.h>


int main(){
int n;
char arr[n];
printf("Input length:\n");
scanf("%d",&n);
printf("Input string:\n");
scanf("%s",&arr);
bsort(arr);
printf("%s",arr);



}


void swap(char *x,char *y){
char temp=*x;
*x=*y;
*y=temp;
}

void bsort(char *arr, int n){
int i, j;
for(i=0;i<n;i++){
    for(j=0;j<n;j++){
        if(&arr[j]<&arr[j+1]){
            swap(arr[j],arr[j+1]);
        }
    }
}
}

我不知道我是否搞砸了數據類型、運算符或函數。 當我運行程序時,沒有任何打印出來。 我將不勝感激任何建議。

#include <stdio.h>
#include <string.h>


void reverseString(char* str)
{
    int l, i;
    char *beginPtr, *endPtr, ch;

    // Get the length of the string using this func instead of aking input
    l = strlen(str);

    // Setting the beginPtr
    // to start of string
    beginPtr = str;

    //Setting the endPtr the end of
    //the string
    endPtr = str + l - 1;
    //basically we add the (len-1)
    
    // Swap the char from start and end
    // index using beginPtr and endPtr
    for (i = 0; i < (l - 1) / 2; i++) {

        // swap character
        ch = *endPtr;
        *endPtr = *beginPtr;
        *beginPtr = ch;

        // update pointers positions
        beginPtr++;
        endPtr--;
    }
}

// Driver code
int main()
{

    // Get the string
    
    char str[100];
    printf("Enter a string: ");

    scanf("%s",&str);

    // Reverse the string
    reverseString(str);

    // Print the result
    printf("Reverse of the string: %s\n", str);

    return 0;
}

如果您不想使用 string.h,我會嘗試使用注釋來解釋這段代碼,然后您可以詢問輸入字符串的長度

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM