Skip navigation.

Đếm từ dài nhất trong chuỗi

Cho S là một chuỗi ký tự. Giả sử các từ trong s là các chuỗi con khác rỗng được phân cách nhau bởi các khoảng trắng. Hãy viết chương trình nhập vào chuỗi s từ bàn phím và thực hiện các công việc sau:
1/ Đếm số lượng từ có trong s.
2/ Cho biết vị trí của từ dài nhất có trong chuỗi(Nhieu tu co chieu dai bang nhau se lay tu dau tien).
VD:
input: ky thuat lap trinh chuoi
output: Tu dai nhat la tu: thuat
O vi tri thu: 3

//Nguyen Van Don
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
#include<stdio.h>
void nhap(char *s);
int dem(char *s);
int tu(char *s,int vt);
void tudainhat(char *s);
//-------------------------------
void tudainhat(char *s)
{
int max=tu(s,0),mf=0;
for(int i=1;i<strlen(s);i++)
if(s!=' '&& s[i-1]==' ')
{
if(max<tu(s,i))
{
max=tu(s,i);
mf=i;
}
}

cout<<endl<<"Tu dai nhat co :" <<max<<" ky tu"<<endl;
cout<<"Tu do la: ";
int j=mf;
while(j<strlen(s)&& s[j]!=' ')
{
cout<<s[j];
j++;
}
}
int tu(char *s,int vt)
{
int c=0,i=vt;
while(i<strlen(s) && s!=' ')
{
c++;
i++;
}
return c;
}
int dem(char *s)
{
int d=0;
for(int i=0;i<strlen(s);i++)
if(s!=' '&& s[i+1]==' ')
d++;

if(s[strlen(s)-1]!=' ')
d++;
return d;
}
void nhap(char *s)
{
cout<<endl<<"Nhap vao chuoi s1: ";
gets(s);
}

//---------------------------------------
void main()
{
clrscr();
char *s;
s= new char[60];
nhap(s);
cout<<endl<<"So tu co trong chuoi la: "<<dem(s);
tudainhat(s);
delete s;
getch();
}

BÀI TẬP CTDLĐịnh dạng chuỗi

How to use Quote function:

  1. Select some text
  2. Click on the Quote link

Write a comment

Comment
(BBcode and HTML is turned off for anonymous user comments.)

If you can't read the words, press the small reload icon.


Smilies