+ 1

Finding a letter in the string which corresponds to that number.

You are making a program that works with text. It needs to take a word and an index number from input, and output the letter with that index in the word. Task: Take a string and a number from input, then output the letter in the string, which corresponds to that number.

4th Oct 2024, 12:48 AM
Prakash Kumar Jaiswal
Prakash Kumar Jaiswal - avatar
6 Answers
+ 5
Prakash Kumar Jaiswal if you initialize the input buffer, filling it with nulls, then you can reliably determine whether the index is out of range simply by checking for null. #include <stdio.h> int main() { char word[50] = {}; //all nulls unsigned int position; scanf("%49s",word); //limit length scanf("%u", &position); if(position<50 && word[position]) printf("%c\n", word[position]); else puts("Position is out of range."); return 0; }
4th Oct 2024, 2:25 PM
Brian
Brian - avatar
+ 3
Prakash Kumar Jaiswal you can still iterate even without using strlen, just stop when you hit the null terminator '\0'. #include <stdio.h> int main() { char word[50]; int position; scanf("%s",word); scanf("%d", &position); for(int i=0;word[i]!='\0';i++){ if(word[i]==word[position]){ printf("%c\n", word[i]); return 0; } } puts("Position is out of range."); return 0; }
4th Oct 2024, 10:05 AM
Bob_Li
Bob_Li - avatar
+ 2
Show your efforts first!
4th Oct 2024, 3:44 AM
`ᴴᵗᵗየ
`ᴴᵗᵗየ - avatar
4th Oct 2024, 4:48 AM
BroFar
BroFar - avatar
+ 2
BroFar , Thanks for the detailed information, I'm looking forward to next time whenever I post a problem.
4th Oct 2024, 9:16 AM
Prakash Kumar Jaiswal
Prakash Kumar Jaiswal - avatar
+ 1
`ᴴᵗᵗየ , I already solved this problem but I stuck in without using the string library file. Is it possible to perform the same operation without using the string library file. My effort was this: #include <stdio.h> #include<string.h> int main() { char word[50]; int position; scanf("%s",word); scanf("%d", &position); // Check if the index is valid if (position >= 0 && position < strlen(word)) { printf("%c\n", word[position]); } else { printf("Position is out of range.\n"); } return 0; }
4th Oct 2024, 9:12 AM
Prakash Kumar Jaiswal
Prakash Kumar Jaiswal - avatar