How to output string second word first letter? - c++

I need solution for this code, its almost done, but i dont understand how i can get first letter from second word, not first? In this code i get 1st letter of first word and dont know how to fix, to get first letter from second word of string which is input from user.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s, krt;
int sk;
cout << "Enter Array: ";
getline(cin, s);
sk = s.length();
cout << "Character in string: " << sk << endl;
int i, vst = 0, bas = 0;
for (i = 0; i < sk; i++) {
krt = s.substr(i, 1);
if (krt == " ")
vst = vst + 1;
}
cout << "Spaces count in string: " << vst << endl;
char tpb;
tpb = s[0];
int pbk;
pbk = tpb;
cout << "String second word first letter: " << tpb << " and its ASCII code: " << pbk << endl;
return 0;
}
Hope you understand what i need to get.

The main problem is that you use 0 as the index, instead of storing the index you want; the first non-space character that follows a space. At least, that is the definition I am going to assume - you didn't specify what to do for multiple consequetive spaces, nor strings containing non-alphabetic characters, such as "function()", where vim would say that '(' is the first character of the second word. Extending the code below to do that is left as an excercise to the reader.
There are a lot of other issues in your code; declarations that can be joined with the definition, doing a string comparison where you only need to compare a single character, and using for loops where there are algorithms to choose instead. Together these add a lot of noise to the code.
Finally, you need some code to handle the case of not having a second word, in order to not get undefined behaviour as in #Diodacus's code.
With regular for-loops:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
cout << "Enter Array: ";
getline(cin, s);
const int sk = s.length();
cout << "Character in string: " << sk << endl;
int vst = 0;
bool space_has_passed = false;
int first_nonspace_after_space_index = -1;
for (int i = 0; i < sk; i++) {
if (s[i] == ' ') {
vst = vst + 1;
space_has_passed = true;
} else if (space_has_passed && first_nonspace_after_space_index == -1) {
first_nonspace_after_space_index = i;
}
}
cout << "Spaces count in string: " << vst << endl;
if ( first_nonspace_after_space_index != -1 && sk > first_nonspace_after_space_index) {
const char tpb = s[first_nonspace_after_space_index];
const int pbk = tpb;
cout << "String second word first letter: " << tpb << " and its ASCII code: " << pbk << endl;
} else {
cout << "Need at least two words" << endl;
}
return 0;
}
You can cut it down by 7 lines if you use <algorithms>:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string s;
cout << "Enter Array: ";
getline(cin, s);
const int sk = s.length();
cout << "Character in string: " << sk << endl;
auto first_space = std::find(s.begin(), s.end(), ' ');
auto first_nonspace_afterspace = std::find_if(++first_space, s.end(), [](const char & c){ return c != ' '; });
int count_spaces = std::count(s.begin(), s.end(), ' ');
cout << "Spaces count in string: " << count_spaces << endl;
if( first_nonspace_afterspace != s.end() ) {
const char tpb = *first_nonspace_afterspace;
const int pbk = tpb;
cout << "String second word first letter: " << tpb << " and its ASCII code: " << pbk << endl;
} else {
cout << "Need at least two words" << endl;
}
return 0;
}

I suggest you to take a brief look at the string class documentation page (http://www.cplusplus.com/reference/string/string/), there is a lot of function that can help you manipulate string.
Based on the functions available in this class (eg. cbegin(), cend(), find(), c_str(), etc.), you could do something like this:
#include <iostream>
#include <string>
#include <ctype.h>
using namespace std;
int main()
{
string s;
cout << "Enter array: ";
getline(cin, s);
int sk = s.length();
cout << "Character in string: " << sk << endl;
int vst = 0;
for (auto i=s.cbegin(); i!=s.cend(); ++i)
if(isspace(*i)) vst++;
cout << "Spaces count in string: " << vst << endl;
string t = s.substr(s.find(" ") + 1, 1);
char tpb = *t.c_str();
int pkt = tpb;
cout << "String second word first letter: " << tpb << " and its ASCII code: " << pkt << endl;
return 0;
}
The main problem is that you print the first letter of the string passed in parameter:
tpb = s[0];
You should either:
memorize the index of the location of the first char of the second word
or
get the second word of the string passed in parameter and print the first char of this string
Finally, what is happening when there is only one word passed ?
You should also think about that. In the code above, if you pass the word test the program prints anyway String second word first letter: t and its ASCII code: 116 which is not true.

Try this:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string s, krt;
int sk;
cout << "Enter Array: ";
getline (cin, s);
sk = s.length();
cout << "Character in string: " << sk << endl;
int i, vst = 0, bas = 0;
for (i = 0; i < sk; i++)
{
krt = s.substr(i, 1);
if (krt == " ") vst = vst + 1;
}
cout << "Spaces count in string: " << vst << endl;
char tpb;
for (i = 0; i < sk; ++i) // Searching for first space
{
if (s[i] == ' ')
break;
}
tpb = s[i + 1];
int pbk;
pbk = tpb;
cout << "String second word first letter: " << tpb << " and its ASCII code: " << pbk << endl;
return 0;
}
This should do the trick.

Related

why does this stop after the space

I need some help checking if the string is a space and then shifting it by one char in the Alphabet I can get the first word but not any after the space.
string Alphabet = "abcdefghijklmnogqrstuvwxyz ";
cout << "Enter your string > " << flush;
cin >> OldString;
int Length = OldString.length();
for (int i = 0; i < Length; i++) {
if(OldString[i] == Alphabet[26]){
NewString = NewString + Alphabet[26] ;
cout << "string found" << endl;
}
else {
Result = Alphabet.find(OldString[i], 0);
cout << Result << endl;
NewString = NewString + Alphabet[Result + 1];
}
}
cin is looking for the end of input string by searching for the first whitespace in the string.
You should rather use std::getline instead.
So your code is going to look like this:
#include <iostream>
#include <string>
std::string OldString;
string Alphabet = "abcdefghijklmnogqrstuvwxyz ";
cout << "Enter your string > " << flush;
std::getline(std::cin, OldString);
int Length = OldString.length();
for (int i = 0; i < Length; i++) {
if(OldString[i] == Alphabet[26]){
NewString = NewString + Alphabet[26] ;
cout << "string found" << endl;
}
else {
Result = Alphabet.find(OldString[i], 0);
cout << Result << endl;
NewString = NewString + Alphabet[Result + 1];
}
}

Prompt the user for a word then check it for double characters

I'm trying to check a word for repeated letters. For example, words like "supercalifragilisticexpialidocious," and "emphasis," should not have any double letters in it, but words like "different," "mississippi," and "formatting" should. This is what I have at the moment:
You are close, but your approach is using the wrong data type for the input, and it is outputting the result incorrectly.
Try something more like this instead:
#include <iostream> // for cout and cin
#include <string> // for string commands
using namespace std;
bool hasDoubleChars(const string &str) {
for (size_t i = 1; i < str.size(); ++i) {
if (str[i] == str[i-1]) {
return true;
}
}
return false;
}
int main() {
string str;
cout << "Welcome to the DoubleChecker(TM) word checker" << endl;
cout << "=============================================" << endl;
cout << "Enter a word to check: " << endl;
cin >> str;
if (hasDoubleChars(str)) {
cout << "There are double characters in the word " << str << ".";
} else {
cout << "There are no double characters in the word " << str << ".";
}
cout << endl;
return 0;
}
Live Demo
You can loop through each character of a string, then compare the next character in the string to the previous.
Example
#include <iostream>
int main()
{
std::string str = "Mississippi";
for (int i = str.size(); i > 0; i--)
if (str[i] == str[i-1])
std::cout << "- " << str[i] << std::endl;
return 0;
}

Trying to find even length substrings from index 0 onwards

I am trying to find even length substrings from the string "000000".It worked fine till index 2 after that it's not producing desired output.My IDE was showing exception unhandled at line :str2=str1.substr(i,k);
#include <iostream>
#include<string>
using namespace std;
int main()
{
string str = "000000";
string str2, str1;
int i = 0;
while (i < str.length())
{
int k = 2;
str1 = str.substr(i);
cout << "\n new substring from " << i << " pos is ";
cout<<str1 << endl;
int len = str1.length();
cout << len << endl;
while (k <= len)
{
cout << "\n" << i << " " << k;
str2 = str1.substr(i, k);
cout << endl << str2;
k = k + 2;
str2.clear();
}
i++;
str1.clear();
}
}
It seems this statement
str2 = str1.substr(i, k);
^^^
does not make sense.
You mean
str2 = str1.substr(0, k);
^^^

Display duplicate characters in a string

I wrote some code in C++ to display duplicate characters in a string, but if a character is repeated more than three times, the code prints the repeated character more than once.
For example if the string is aaaddbss, it should only print out ads but it prints aaads instead.
What am I doing wrong?
cout << " Please enter a string" << endl;
cin.getline(input, 100); // example input (ahmad wahidy) the output reads a a h a d instead of a h d
for (int i = 0;input[i]!='\0'; i++)
{
for (int j = i+1;input[j]!='\0'; j++)
{
if (input[i] == input[j])
{
cout << input[i] << " ";
}
}
}
cout << endl;
Instead of using your own custom methods, why not use a short and standard method?
Given an std::string input with the text, this will print the unique chars:
std::set<char> unique(input.begin(), input.end());
for (auto & c : unique)
{
std::cout << c << " ";
}
std::cout << std::endl;
You can use std::count and std::set:
#include <string>
#include <set>
#include <iostream>
using namespace std;
int main()
{
string s = "hellohowareyou";
set<char>the_set(s.begin(), s.end());
for (char i:the_set)
if (count(s.begin(), s.end(), i) > 1)
cout << i << endl;
}
Output:
e
h
l
o
If you are not allowed to use a map (and probably also not allowed to use a set), you could simply use an array of integers to count occurrences, with one entry for each possible char value. Note that a character - when taken as an ASCII value - can be directly used as an index for an array; however, to avoid negative indices, each character value should first be converted to an unsigned value.
#include <iostream>
#include <limits>
int main() {
const char* input = "aaaddbss";
int occurrences[UCHAR_MAX+1] = { 0 };
for (int i = 0;input[i] !='\0'; i++)
{
unsigned char c = input[i];
if (occurrences[c]==0) {
occurrences[c]++;
}
else if (occurrences[c]==1) {
occurrences[c]++;
cout << "duplicate: " << c << endl;
}
}cout << endl;
}

Anagram detection method c++. Problems converting string to ascii value

For anyone that might be able to help me figure this out. I am creating a method that will compare two strings and detect whether they are an anagram or not. An anagram is two strings that have the same letters, though they may be in a different order. For example "listen" and "iltsen" are anagrams.
I have decided to break the strings up into char arrays. I know that is working correctly because I tested it using cout on each array element. Next is where it goes wrong. I attempt to use the ASCII value of each char and add it to a variable for each array. This would mean that if the values match then they must be an anagram.
However for whatever unknown reason it is not working correctly. I am finding that it is reading index 0 twice for one array and not for the other. I am so confused beyond reason. I have absolutely no idea what this is occurring. I have tried multiple different solutions and had no luck finding out the problem. If anyone has any idea whats going on here I would greatly appreciate the help.
-Thanks!
#include "stdafx.h"
#include <iostream>
#include <string>
#include <math.h>
#include <iomanip>
#include <cctype>
#include <vector>
using namespace std;
bool isAnagram(string s1,string s2)
{
static char firstString[] = { 'c' };
static char secondString[] = { 'c' };
int size = s1.length();
static int count1 = 0;
static int count2 = 0;
cout << s1 << endl;
cout << s2 << endl;
if (s1.length() == s2.length())
{
for (int i = 0; i < size; i++)
{
firstString[i] = s1.at(i);
cout << i;
}
for (int i = 0; i < size; i++)
{
secondString[i] = s2.at(i);
cout << i;
}
cout << endl;
for (int i = 0; i < size; i++)
{
count1 = count1 + (int)firstString[i];
cout << "first" << i << ": " << firstString[i] << " = " << (int)firstString[i] << endl;
count2 = count2 + (int)secondString[i];
cout << "second" << i << ": " << secondString[i] << " = " << (int)secondString[i] << endl;
}
cout << count1 << " and " << count2 << endl;
if (count1 == count2)
return true;
}
else
return false;
count1 = 0;
count2 = 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
static char end;
do
{
string s1;
string s2;
cout << "Please enter the first string: ";
cin >> s1;
cout << endl << "Please enter the second string: ";
cin >> s2;
bool result = isAnagram(s1, s2);
static string resultString;
if (result == true)
resultString = "True";
else
resultString = "False";
cout << endl << "Anagram test result: " << resultString << endl;
cout << endl << "enter E for end or any other key to run again: ";
cin >> end;
cout << "----------------------------------------" << endl;
} while (end != 'e' && end != 'E');
return 0;
}
It's not useful to use static variables in your case, without them you wouldn't need the last 2 lines of isAnagram.
It's also useless to store both strings in char arrays because you can use them directly in your 3rd loop(also you are overflowing your buffer which has a size of 1)
for (int i = 0; i < size; i++)
{
std::cout << count1 << " ";
count1 = count1 + (int)s1.at(i);
cout << "first" << i << ": " << s1.at(i) << " = " << (int)s1.at(i) << endl;
count2 = count2 + (int)s2.at(i);
cout << "second" << i << ": " << s2.at(i) << " = " << (int)s2.at(i) << endl;
}
Also you can't say that 2 strings do contain the same letters by comparing the sum of their ASCII values, thats like saying 3 + 4 is the same as 2 + 5 because both give 7.
You could create an array of 52 ints, each element is a counter for its own letter, then you could loop over both strings with one loop where each letter of the first string is incrementing its element in the array and the second strings letters are decrementing elements.
if (s1.length() != s2.length())
return false;
std::vector<int> counts(52);
for (unsigned int i = 0; i < s1.length(); ++i)
{
++counts[s1[i] - (s1[i] < 91 ? 65 : 71)];
--counts[s2[i] - (s2[i] < 91 ? 65 : 71)];
}
be sure that the array is initialized to 0.
At the end you need to loop over the array, if one of the elements is not 0 it's not an anagram, else return true.
for (unsigned int i = 0; i < 52; ++i)
if (counts[i] != 0)
return false;
return true;