检查字符串是否仅包含使用.at(int)的唯一字符

时间:2017-06-04 12:23:13

标签: c++

真正基本的问题,但我无法弄清楚这一点。我的程序通过将数组中每个ASCII的标志设置为true(如果在字符串中找到)来检查字符串是否唯一。它没有工作(它编译,但没有给出正确的答案),我无法解释为什么会这样做。

我得到的输出是0:

的main.cpp

#include "main.hpp"
#include <iostream>

bool isUnique(std::string str) {

    if(str.length() > 128)
        return false;

    bool theChars[128];

    for(int i = 0; i < str.length(); i++) {
        int loc = str.at(i);

        if(theChars[loc])
            return false;
        else
            theChars[loc] = true;
    }

    return true;
}

int main() {

    std::string timmy = "abcdefghijklmnop";
    std::cout << isUnique(timmy);

    return 0;
}

3 个答案:

答案 0 :(得分:2)

你忘了初始化bool数组:

bool theChars[128] = {};

空的初始化程序意味着&#34;使用默认值&#34;这是零,对于布尔来说也是假的。

P.S。如果[0,127]之外有任何字符,则代码会产生未定义的行为。您可以通过使theChars 256长并在编制索引之前将字符转换为uint8_t来解决此问题。或者如果超出范围,请使用std::array<char, 128>theChars.at(loc)抛出异常。

答案 1 :(得分:1)

更简单的方法是使用set

#include <iostream>
#include <set>
using namespace std;
bool isUnique(string str) {
    set<char>st(str.begin(),str.end());
    if(st.size()==str.size())
        return true;
    return false;
}

int main() {

    string timmy = "abcdefghijklmnop";
    cout << boolalpha<<isUnique(timmy)<<endl;
    timmy = "aaaaabbbcdefghijklmnop";
    cout << boolalpha<<isUnique(timmy)<<endl;
    return 0;
}

P.S。如果不使用boolalpha,则会为true打印1,为false打印0。

答案 2 :(得分:0)

Sub New()
End Sub

Structure APPBARDATA
    Friend cbSize As Integer
    Friend hWnd As IntPtr
    Friend uCallbackMessage As Integer
    Friend uEdge As Integer
    Friend rc As RECT
    Friend lParam As IntPtr
End Structure

Friend Declare Function SHAppBarMessage Lib "shell32.dll" Alias "SHAppBarMessage" (ByVal dwMessage As Integer, ByRef pData As APPBARDATA) As IntPtr
Friend Declare Function GetSystemMetrics Lib "User32.dll" Alias "GetSystemMetrics" (ByVal index As Integer) As Integer
Friend Declare Function MoveWindow Lib "User32.dll" Alias "MoveWindow" (ByVal hWnd As IntPtr, ByVal x As Integer, ByVal y As Integer, ByVal cx As Integer, ByVal cy As Integer, ByVal repaint As Boolean) As Boolean
Friend Declare Auto Function RegisterWindowMessage Lib "User32.dll" (ByVal msg As String) As Integer

<DllImport("user32.dll", CharSet:=CharSet.Unicode)>
Friend Shared Function FindWindow(strClassName As String, strWindowName As String) As IntPtr
End Function

这不使用任何额外的空格,适用于任何字符编码。