// This program reads in lines of text and extracts the nth word in each line.
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();
System.out.println("a"+word);
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 );
}
}
java 里的nextInt() hasNextline() 在C語言內要怎么實作。
uj5u.com熱心網友回復:
比如char *s;
int n;
while((s=gets()) != NULL) { //這里相當于hasNextLine
sscanf(s, “%d”, &n);//這里相當于nextInt
printf(“%d”, n);
}
uj5u.com熱心網友回復:
建議樓主描述一下需求,根據需求去用C實作~轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/257884.html
標籤:C語言
下一篇:我用vs,為什么不能除錯成功
