In: Computer Science
I need convert this java code to C language. There is no string can be used in C. Thank you!
import java.util.Scanner;
public class Nthword
{
public static void main( String args[] )
{
String line;
int word;
Scanner stdin = new Scanner(System.in);
while ( stdin.hasNextLine() )
{
line = stdin.nextLine();
word = stdin.nextInt(); stdin.nextLine(); // get rid of the newline
after the int
System.out.println( "Read line: \"" + line + "\", extracting
word [" + word + "]" );
System.out.println( "Word #" + word + " is: " + extractWord( line,
word ) );
}
stdin.close();
System.out.println( "\nEnd of processing" );
}
// returns the first word of the string
private static String extractWord( String theLine, int word )
{
int start;
int end;
int spaces = 1;
String result = "";
// search for the nth non-blank character
for (start = 0; start < theLine.length() && spaces <
word; start++)
{
if ( Character.isSpaceChar( theLine.charAt( start ) ) )
{
spaces++;
}
}
// only need to continue if we haven't gone past the end of the
string
if ( start<theLine.length() )
{
// the next blank character is the end
for ( end=start ; end<theLine.length() &&
!Character.isSpaceChar( theLine.charAt( end ) ) ; end++ )
;
// we now have the word
result = theLine.substring( start, end );
}
return( result );
}
}
Following is the C language implementation of the given Java code. The code uses character array to process strings.
C CODE:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
// Function to extract the word, from the given index.
const char * ExtractWord(char line[], int word, char result[])
{
int i, j =0, ctr = 0;
char wordList[10][10]; // Array to store each word
separately.
// For loop separates the line into separate
words.
for(i=0;i<=(strlen(line));i++) {
// Assign NULL into
wordList[], if NULL or spaces are encountered in the line.
if(line[i]=='
'||line[i]=='\0') {
wordList[ctr][j]='\0';
ctr++; // Scan next word
j=0; // index is set to 0 for a new word
}
else {
wordList[ctr][j]=line[i];
j++;
}
}
// Check if index exceeds word limit.
if(strlen( *wordList) < word) {
printf("\nIndex is out of bound,
exiting now.");
exit(1);
}
// Extract the word from the given index from
wordList[] and assign it to result.
for(i=0;i < ctr;i++) {
if(i == word) {
strcpy(result,
wordList[i]);
}
}
return result;
}
// Main driver function
int main() {
char line[100], result[20];
int word, i, j;
printf("\nEnter a line: ");
scanf("%[^\n]",line);
getchar(); // Get rid of newline char after
scanf()
printf("\nEnter the word index to extract:
");
scanf(" %d", &word);
// Invoke the function to extract the word
strcpy(result, ExtractWord(line, word-1,
result));
printf("\nLine is: %s", line);
printf("\nExtracted word at index %d is %s.", word,
result);
return 0;
}
OUTPUT:
Feel free to ask any doubt related to this answer in the comment section below. Do leave a thumbs up if this helps.