0

The string input format is like this

str1 str2

I DONT know the no. of characters to be inputted beforehand so need to store 2 strings and get their length. Using the C-style strings ,tried to made use of the scanf library function but was actually unsuccessful in getting the length.This is what I have:

// M W are arrays of char with size 25000
   while (T--)
   {
       memset(M,'0',25000);memset(W,'0',25000);
       scanf("%s",M);
       scanf("%s",W);
       i = 0;m = 0;w = 0;
       while (M[i] != '0')
              {
                  ++m; ++i;  // incrementing till array reaches '0'
              }
        i = 0;
       while (W[i] != '0')
              {
                  ++w; ++i;
              }
       cout << m << w;


   }

Not efficient mainly because of the memset calls.

Note: I'd be better off using std::string but then because of 25000 length input and memory constraints of cin I switched to this.If there is an efficient way to get a string then it'd be good

4

3 回答 3

2

除了已经给出的答案之外,我认为您的代码略有错误:

   memset(M,'0',25000);memset(W,'0',25000);

您真的是要使用字符零(值 48 或 0x30 [假设 ASCII 在某些学究拒绝我的答案并指出还有其他编码])或 NUL(值为零的字符)填充字符串。后者是0,不是'0'

   scanf("%s",M);
   scanf("%s",W);
   i = 0;m = 0;w = 0;
   while (M[i] != '0')
          {
              ++m; ++i;  // incrementing till array reaches '0'
          }

如果您正在寻找字符串的结尾,则应该使用0,而不是'0'(如上所述)。

当然,scanf0为你在字符串的末尾加上一个 a,所以不需要用0[or '0'] 填充整个字符串。

Andstrlen是一个现有的函数,它将给出 C 样式字符串的长度,并且很可能有一个比仅检查每个字符并增加两个变量更聪明的算法,使其更快[至少对于长字符串]。

于 2013-05-12T08:30:28.650 回答
1

memset使用时不需要scanf,scanf 将终止符添加'\0'到字符串中。

此外,strlen确定字符串长度的更简单方法:

scanf("%s %s", M, W); // provided that M and W contain enough space to store the string
m = strlen(M); // don't forget #include <string.h>
w = strlen(W);
于 2013-05-12T08:23:14.677 回答
0

没有 memset 的 C 风格 strlen 可能如下所示:

#include <iostream>
using namespace std;

unsigned strlen(const char *str) {
    const char *p = str;
    unsigned len = 0;
    while (*p != '\0') {
        len++;
        *p++;
    }
    return len;
}

int main() {
    cout << strlen("C-style string");
    return 0;
}

14号回来了。

于 2014-10-05T06:16:09.193 回答