Showing posts with label string. Show all posts
Showing posts with label string. Show all posts

Thursday, 1 January 2015

Needle in the haysack (spoj) (solved just by using the c++ string fucntions)

link to question http://www.spoj.com/problems/NHAY/

#include<stdio.h>
#include<iostream>
#include<string>
using namespace std;
int main()
{   int t;
//    scan
    string a,b;
    int f=-1;
    while(cin>>t>>a>>b)
    {
        do{//int k=a.length();
     f=b.find(a,f+1);
     if(f!=-1)
        cout<<f<<endl;}while(f!=-1);
printf("\n");
    }
 
}


The find function returns the first position where the string is found ,
The second parameter allows the substring to be found in the original string after a particular position , and since we want the next substring to be found after the found result , be initialize f with -1 and always search with f+1 ,
if the sunstring is not found , the find function returns -1 .
:)

Monday, 22 December 2014

cin which can take SPACE as input

http://stackoverflow.com/questions/24028603/taking-space-separated-string-input-in-c

eg

1down voteaccepted
#include <iostream>
#include <string>

int main(){

std::string str;
std::getline(std::cin, str);
std::cout << "I just read in " << str;

return 0;}


sorting bank accounts (map)(spoj)

Its a simple question which demands use of map and good control on string .
There is a question with good combination of both and though simple offers many things to learn.

http://www.spoj.com/problems/SBANK/

#include<stdio.h>
#include<map>
#include<string>
#include<iostream>
using namespace std;
int main()
{
int t,p;
freopen("kr.in","r",stdin);
map <string, int> cal;
map <string, int> :: iterator it;
char st[10000];

scanf("%d",&t);
while(t--)
{
    scanf("%d",&p);
    char c;
    scanf("%c",&c);
    for(int i=0;i<p;i++){
          //  fflush(stdin);
    gets(st);
    //puts(st);
    cal[st]++;}

    for(it=cal.begin();it!=cal.end();it++)
{
   // cout<<it->first<<" ";
    printf("%s %d\n",it->first.c_str(),it->second);
}
printf("\n");
cal.clear();
}
}

things learnt 

if we use string it becomes difficult to take input via gets
anyways its imp to take a char input to remove the new line character from getting into gets
if we want to print the string which is the key via printf , we need to use it->first.c_str() , 

most importantly , we cannot take string (which is a object input through scanf or gets ) which are functions of cpp and if we use just cin we will be unable to string input with space.