Created
November 15, 2024 17:29
-
-
Save juanfal/4dce7934f0da9dce7fb0030302ac2673 to your computer and use it in GitHub Desktop.
word n of a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 07.nword.cpp | |
// juanfc 2024-11-15 | |
// | |
#include <iostream> | |
using namespace std; | |
int main() | |
{ | |
string wordn(string s, int n); | |
cout << wordn("I. to Programming", 1) << endl; // I | |
cout << wordn("I. to Programming", 2) << endl; // to | |
cout << wordn("I. to Programming", 3) << endl; // Programming | |
cout << wordn("I. to Programming", 4) << endl; // | |
return 0; | |
} | |
// functions | |
string wordn(string s, int n) | |
{ | |
bool partOfWord(char c); | |
string r; | |
int cnt = 0, i = 0; | |
bool onWord = false; | |
while (i < s.size() and cnt <= n) { | |
if (partOfWord(s[i])) { | |
if (not onWord) | |
cnt++; | |
if (cnt == n) | |
r += s[i]; | |
onWord = true; | |
} else | |
onWord = false; | |
++i; | |
} | |
return r; | |
} | |
bool partOfWord(char c) | |
{ | |
return (('A' <= c) and (c <= 'Z')) or | |
(('a' <= c) and (c <= 'z')); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment