C++中char[]的子串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15586586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:30:58  来源:igfitidea点击:

Substring of char[] in c++

c++charsubstring

提问by Yoda

I have

我有

  char t[200];
  cin.get(s, 200);
  int i = 5; 
  int j = 10;

Is there any simple way to get substriing(i,j)from tbeside copying every element seperately to the another array? No stringsetc. just char t[200].

有没有简单的方法来获得substriing(i,j)t每个元素seperately复制到另一个阵列旁边?没有strings等只是char t[200]

采纳答案by NPE

If you are allowed to modify t, you could set t[j]to 0and then use t + ito get the substring.

如果你被允许修改t,你可以设置t[j]0然后使用t + i来获取子字符串。

If not, you are going to have to make a copy.

如果没有,您将不得不复制。

That said, why can't you just use std::stringand save yourself the headache?

也就是说,你为什么不能直接使用std::string并避免头痛呢?

回答by Jean-Baptiste Yunès

If you need only to read the data then t+i is what you want, alas you'll have to manage the length of your substring...

如果您只需要读取数据,那么 t+i 就是您想要的,唉,您必须管理子字符串的长度...

char *sub = t+i;
int len = j-i;
printf("%.*s\n",len,sub);

If you need to have a distinct copy of the substring, then you must copy.

如果您需要具有子字符串的不同副本,则必须进行复制。

回答by Mayhem

This should work fine:

这应该可以正常工作:

#include <string.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

int main()
{
 char t[200];
 cin.get(t, 200);
 int i = 5; 
 int j = 10;
 char *to = (char*) malloc(j-i+1);
 strncpy(to, t+i, j-i);
 to[j-i]='
char* to = new char[j-i+1];
'; cout << to; }

You can use newinstead of malloclike this:

您可以使用new而不是malloc这样:

char* substr(char* arr, int begin, int len)
{
    char* res = new char[len];
    for (int i = 0; i < len; i++)
        res[i] = *(arr + begin + i);
    res[len] = 0;
    return res;
}

回答by spynet41

char const * beg = t+i;
char const * end = t+j+1;    
std::cout.write(beg, end-beg);

回答by Benjamin Lindley

Use two pointers to denote a range within the string.

使用两个指针来表示字符串内的一个范围。

llvm::StringRef sref(t+i, j+1-i);
std:cout << sref;

Or you can use a class that encapsulates this idea. There is something like thatbeing proposed for the standard library. In the meantime, you can write your own, or you can use one from a library. For example, llvm::StringRef.

或者你可以使用一个封装了这个想法的类。有这样的事情正在提议的标准库。同时,您可以自己编写,也可以使用库中的一个。例如,llvm::StringRef

char newt[200];   
// copy j-i chars from position t+i to newt array
strncpy(newt, t + i, j-i);
// now null terminate
newt[j-i] = 0;

回答by suspectus

This does not do any bounds checking to ensure the destination array is large enough

这不会进行任何边界检查以确保目标数组足够大

##代码##