从字符串打印最长的单词及其长度。 [英] Printing the longest word and it's length from a string.

查看:84
本文介绍了从字符串打印最长的单词及其长度。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个程序,它应该扫描一个字符串找到字符串中最长的单词并打印它的长度和单词。但由于某种原因,它无法正常工作。它显示了奇怪的符号。



为了找到它,程序开始用for循环扫描字符串。然后在第一个for循环中有另一个for循环,它找到单词的长度。如果长度大于当前最长的单词,则将单词分配给另一个字符串。



I made a program which should scan a string find the longest word of the string and print it's length and the word. But for some reason it is not working properly. It is showing weird symbols.

To find it the program starts scanning the string with a for loop. Then within the first for loop there is another for loop which finds the length of the word. If the length is greater than the current longest word it assigns the word to another string.

#include<stdio.h>

int main()
{
	char string1[] = "This program finds the longest word", longestword[20];
	int index,letters,longestnumber=0,temp=0,j;
	
	for(index=0;string1[index]!='\0';index++)
	{
		temp = index;
		
		for(letters=0;string1[index]!=' ' && string1[index]!='\0' ;index++,letters++);
		
		j=0;
		
		if(letters>=longestnumber)
		{
			while(string1[temp] != ' ')
			{
				longestword[j] == string1[temp];
				temp++;
				j++;
			}
		}
	}
	
	printf("%d %s",longestnumber,longestword);
	
	return 0;
}





我的尝试:



我认为这将是一个无限循环,但事实并非如此。相反,它以奇怪的符号结尾。



What I have tried:

I thought it would be a infinite loop but it is not. Instead it is ending with weird symbols.

推荐答案

您没有将字符复制到 longestword ,正确的分配运算符是一个 = 符号。您还需要在 longestword 的末尾添加一个空字符('\ 0'),如下所示:

You are not copying the characters into longestword, the correct assignment operator is a single = sign. You also need to add a null character ('\0') at the end of longestword, as follows:
while(string1[temp] != ' ')
    {
        longestword[j] = string1[temp]; // single = sign for assignment
        temp++;
        j++;
    }
    longestword[j] = '\0'; // add terminating null
    longestnumber = letters; // save the value of longest word here
}
if (string1[index] == '\0')
    break;


你的内部for循环
for(letters=0;string1[index]!=' ' && string1[index]!='\0' ;index++,letters++);

没有正文,总是从零开始运行。

我认为它应该从索引运行。最长编号未设置,您必须以零结束最长字。



您可以使用C函数strtok分割字符串和使用子字符串。



您的代码没有按预期工作。如何使用调试器?

has no body and run always from zero.
I think it should run from index. Longestnumber isnt set and you must terminate the longestWord with a zero.

You can use the C function strtok for splitting a string and the use of substrings.

Your code isnt working as you expect. What about using the debugger?


转换为托管C#(或C ++?),并使用string.Split函数从字符串中创建单词数组。



然后你有很多方法可以找到最长的单词。



但首先,你必须来到光明;走出无管理的黑暗。
Convert to "managed" C# (or C++ ?), and use the "string.Split" function to create an array of "words" from your string.

You then have a number of ways to find the longest word.

But first, you must come to the light; out of the darkness that is "unmanaged".


这篇关于从字符串打印最长的单词及其长度。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆